过期事件通过Redis的订阅与发布功能(pub/sub)来进行分发。
redis服务端配置
超时的监听,并不需要自己发布,只有修改配置文件redis.conf中的:notify-keyspace-events Ex,默认为notify-keyspace-events “”
因为开启键空间通知功能需要消耗一些 CPU , 所以在默认该功能处于关闭状态。
可以通过修改 redis.conf 文件, 或者直接使用 CONFIG SET 命令来开启或关闭键空间通知功能:
CONFIG GET notify-keyspace-eventsCONFIG SET notify-keyspace-events Ex
- 当
notify-keyspace-events选项的参数为空字符串时,功能关闭。 - 另一方面,当参数不是空字符串时,功能开启。
notify-keyspace-events 的参数可以是以下字符的任意组合, 它指定了服务器该发送哪些类型的通知
输入的参数中至少要有一个 K 或者 E , 否则的话, 不管其余的参数是什么, 都不会有任何通知被分发。
示例
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.listener.RedisMessageListenerContainer;@Configurationpublic class RedisListenerConfig {@BeanRedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}}
import cn.ws.constants.OrderConstants;import org.springframework.data.redis.connection.Message;import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;import org.springframework.data.redis.listener.RedisMessageListenerContainer;import org.springframework.stereotype.Component;@Componentpublic class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {super(listenerContainer);}/*** Redis-key失效监听事件,所有key 失效都会走此方法** @param message* @param pattern*/@Overridepublic void onMessage(Message message, byte[] pattern) {// 获取失效的keyString expiredKey = message.toString();// 指定key 的前缀=xxxxxx,处理对应业务逻辑,可看步骤三生成订单号:public static final String ORDER_OVER_TIME_KEY= "order-over-time:";if (expiredKey.indexOf(OrderConstants.ORDER_OVER_TIME_KEY) != -1) {String[] orderOn = expiredKey.split(":");System.out.println("订单号: "+orderOn[1] +"超时" );}System.out.println(expiredKey);}}
更多文章:
http://redisdoc.com/topic/notification.html
参考文章:
https://blog.csdn.net/qq_41463655/article/details/104429713 (订单过期)
