建设信用购物网站,网站常用配色,网站订单系统模板下载,公司装修开工仪式吉利话项目中常常会碰到这样的需求#xff0c;用户下订单后#xff0c;30分钟未完成自动取消订单的功能。有人说这个简单呀#xff0c;写个定时任务就搞定了。除了定时任务之外#xff0c;难道就没有其他的方法来实现吗#xff1f;有--Redis 的键空间通知事件。在Redis 2.8.0之后…项目中常常会碰到这样的需求用户下订单后30分钟未完成自动取消订单的功能。有人说这个简单呀写个定时任务就搞定了。除了定时任务之外难道就没有其他的方法来实现吗有--Redis 的键空间通知事件。在Redis 2.8.0之后提供Keyspace Notifications功能当我们将key,value键值对使用Redis缓存并设置缓存失效时间的时候会触发Redis的键事件通知客户端订阅这个通知服务端将会把对应的通知事件发送给客户端客户端收到通知然后根据自己的不同业务进行处理。要注意的是因为Redis的发布订阅模式采用的是发送即忘的策略当订阅的客户端断线时会丢失所有在断线期间发送给他的事件通知。当你的程序需要一个可靠的事件通知时Redis的键空间通知就不适合了。事件类型键空间通知都会发送两种不同类型的事件消息keyspace 和 keyevent。以 keyspace 为前缀的频道被称为键空间通知key-space notification 而以 keyevent 为前缀的频道则被称为键事件通知key-event notification。开启配置修改Redis的redis.conf# notify-keyspace-events Ex
# By default all notifications are disabled because most users dont need
# this feature and the feature has some overhead. Note that if you dont
# specify at least one of K or E, no events will be delivered.
notify-keyspace-events Ex键空间通知通常是不启用的因为这个过程会产生额外消耗。所以在使用该特性之前请确认一定是要用这个特性的然后修改配置文件# K 键空间通知以__keyspacedb__为前缀
# E 键事件通知以__keyseventdb__为前缀
# g del , expipre , rename 等类型无关的通用命令的通知, ...
# $ String命令
# l List命令
# s Set命令
# h Hash命令
# z 有序集合命令
# x 过期事件每次key过期时生成
# e 驱逐事件当key在内存满了被清除时生成
# A g$lshzxe的别名因此”AKE”意味着所有的事件springboot 中的处理方式添加Redis 消息监听的配置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;/*** ClassName RedisListenerConfig* Description* Author ZhaoDeLin* Date 2019/9/16 15:15* Email: casablanca523163.com**/
Configuration
public class RedisListenerConfig {BeanRedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {RedisMessageListenerContainer container new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}
}
添加Redis key过期事件的监听import lombok.extern.slf4j.Slf4j;
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;
import javax.annotation.Resource;/*** ClassName RedisKeyExpirationListener* Description 监听redis的过期事件* Author ZhaoDeLin* Date 2019/9/16 15:18* Email: casablanca523163.com**/
Component
Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {super(listenerContainer);}public void onMessage(Message message, byte[] pattern){String expiredKey message.toString();log.info(redis key过期{},expiredKey);//业务逻辑处理。。。}
}