过期事件通过Redis的订阅与发布功能(pub/sub)来进行分发。

redis服务端配置

超时的监听,并不需要自己发布,只有修改配置文件redis.conf中的:notify-keyspace-events Ex,默认为notify-keyspace-events “”

因为开启键空间通知功能需要消耗一些 CPU , 所以在默认该功能处于关闭状态
可以通过修改 redis.conf 文件, 或者直接使用 CONFIG SET 命令来开启或关闭键空间通知功能:

  1. CONFIG GET notify-keyspace-events
  2. CONFIG SET notify-keyspace-events Ex
  • notify-keyspace-events 选项的参数为空字符串时,功能关闭。
  • 另一方面,当参数不是空字符串时,功能开启。

notify-keyspace-events 的参数可以是以下字符的任意组合, 它指定了服务器该发送哪些类型的通知
image.png
输入的参数中至少要有一个 K 或者 E , 否则的话, 不管其余的参数是什么, 都不会有任何通知被分发。

示例

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.data.redis.connection.RedisConnectionFactory;
  4. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  5. @Configuration
  6. public class RedisListenerConfig {
  7. @Bean
  8. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
  9. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  10. container.setConnectionFactory(connectionFactory);
  11. return container;
  12. }
  13. }
  1. import cn.ws.constants.OrderConstants;
  2. import org.springframework.data.redis.connection.Message;
  3. import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
  4. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
  8. public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
  9. super(listenerContainer);
  10. }
  11. /**
  12. * Redis-key失效监听事件,所有key 失效都会走此方法
  13. *
  14. * @param message
  15. * @param pattern
  16. */
  17. @Override
  18. public void onMessage(Message message, byte[] pattern) {
  19. // 获取失效的key
  20. String expiredKey = message.toString();
  21. // 指定key 的前缀=xxxxxx,处理对应业务逻辑,可看步骤三生成订单号:public static final String ORDER_OVER_TIME_KEY= "order-over-time:";
  22. if (expiredKey.indexOf(OrderConstants.ORDER_OVER_TIME_KEY) != -1) {
  23. String[] orderOn = expiredKey.split(":");
  24. System.out.println("订单号: "+orderOn[1] +"超时" );
  25. }
  26. System.out.println(expiredKey);
  27. }
  28. }

更多文章:
http://redisdoc.com/topic/notification.html

参考文章:
https://blog.csdn.net/qq_41463655/article/details/104429713 (订单过期)