redis事件通知(notify-keyspace-events Ex)
Keyspace 通知使客户端可以通过订阅频道来接收那些以某种方式改动了 Redis 数据集的事件(触发某些事件后可以向指定的频道发送通知),该功能需 Redis 版本大于 2.8。
问题:
- 设置了生存时间的Key,在过期时能不能有所提示?
- 如果能对过期key一个监听,如何对过期key进行一个回调处理?
Key过期事件的Redis配置
notify-keyspace-events Ex
notify-keyspace-events 的参数为 “Ex”。x 代表了过期事件
ok 重启redis
下面请看代码演示
pom.XML
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.1.9.RELEASE</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.10.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.10.1</version></dependency>
application.yml
redis:host: localhostport: 6379#password: xxxlettuce:pool:max-active: 8 # 连接池最大连接数(使用负值表示没有限制)max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)max-idle: 8 # 连接池中的最大空闲连接min-idle: 0 # 连接池中的最小空闲连接timeout: 3000 # 连接超时时间(毫秒)
RedisConfig.class
package com.example.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.lang.reflect.Method;@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {@Overridepublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... objects) {StringBuffer sb = new StringBuffer();sb.append(o.getClass().getName()).append(method.getName());for (Object object : objects) {sb.append(object.toString());}System.out.println(sb.toString());return sb.toString();}};}@Beanpublic CacheManager cacheManager(LettuceConnectionFactory lettuceConnectionFactory) {RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(json()));return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(lettuceConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();//return RedisCacheManager.create(lettuceConnectionFactory);}@Beanpublic RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate();Jackson2JsonRedisSerializer jsonSerializer = json();StringRedisSerializer stringSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setValueSerializer(jsonSerializer);redisTemplate.setHashKeySerializer(stringSerializer);redisTemplate.setHashValueSerializer(jsonSerializer);redisTemplate.setConnectionFactory(lettuceConnectionFactory);return redisTemplate;}private Jackson2JsonRedisSerializer json() {Jackson2JsonRedisSerializer jsonSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);jsonSerializer.setObjectMapper(om);return jsonSerializer;}@BeanRedisMessageListenerContainer container(LettuceConnectionFactory connectionFactory) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}
}
RedisKeyExpirationListener.class
package com.example.config;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;@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {super(listenerContainer);}
// @Resource
// SeatService seatService;@Overridepublic void onMessage(Message message, byte[] pattern) {String expiredKey = message.toString();if(expiredKey.equals("keyTest")){log.info(expiredKey + "----动作触发");
// seatService.updateToFreeSeat("1");}try {//业务处理} catch (Exception e) {log.error("key 过期通知处理异常,{}", e);}}}
ProductController.class
import com.example.config.CIpProperties;
import com.example.config.NameProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.concurrent.TimeUnit;@Controller
public class ProductController {@Autowired
private StringRedisTemplate stringRedisTemplate;@Autowiredprivate CIpProperties cIpProperties;@Autowiredprivate NameProperties nameProperties;@RequestMapping@ResponseBodypublic String hello(){return "success";}@RequestMapping("/test")@ResponseBodypublic Object test(){stringRedisTemplate.opsForValue().set("keyTest","1",10, TimeUnit.SECONDS);return null;}
}
redis事件通知(notify-keyspace-events Ex)相关推荐
- Redis的事件通知
Redis的事件通知通过发布/订阅模式来实现的. 事件通知分为两种: keyspace 和 kevevent. keyspace称为键空间通知,格式为 __keyspace@DB__:KeyPatte ...
- windows事件id大全_技术转载 || springboot+redis做过期事件通知业务
我的业务场景 系统管理员要给维护员分配巡查路口设施的工作,由于路口比较多,管理员不知道哪些路口已经被分配了,况且过了一个时间周期后,所有的路口要再次被巡查. 思路 我建立了一个表,里面是所有路口和是否 ...
- 键空间通知(keyspace notification)
Redis键空间通知(keyspace notification) 本文档翻译自: http://redis.io/topics/notifications . 键空间通知功能目前仍在开发中,这个文档 ...
- 架构设计:系统存储(16)——Redis事件订阅和持久化存储
接上文<架构设计:系统存储(15)--Redis基本概念和安装使用> 3-4.事件功能和配置项 Redis从2.X版本开始,就支持一种基于非持久化消息的.使用发布/订阅模式实现的事件通知机 ...
- java 事件通知_正确获取Java事件通知
java 事件通知 实现观察者模式以提供Java事件通知似乎是一件容易的事. 但是,容易陷入一些陷阱. 这是我在各种场合不慎造成的常见错误的解释-- Java事件通知 让我们从一个简单的bean St ...
- 正确获取Java事件通知
实现观察者模式以提供Java事件通知似乎是一件容易的事. 但是,容易陷入一些陷阱. 这是我在各种场合不慎造成的常见错误的解释-- Java事件通知 让我们从一个简单的bean StateHolder开 ...
- java后端站内通知_正确使用Java事件通知
通过实现观察者模式来提供 Java 事件通知(Java event notification)似乎不是件什么难事儿,但这过程中也很容易就掉进一些陷阱.本文介绍了我自己在各种情形下,不小心制造的一些常见 ...
- 案例学习BlazeDS+Spring之八InSync06“松耦合”UI同步事件通知
InSync06:增加"松耦合"UI同步事件通知 一.运行DEMO: 1.运行程序:http://localhost:8400/spring-flex-testdrive/insy ...
- epoll边缘触发_epoll事件通知机制详解,水平触发和边沿触发的区别
看到网上有不少讨论epoll,但大多不够详细准确,以前面试有被问到这个问题.不去更深入的了解,只能停留在知其然而不知其所以然.于是,把epoll手册翻译一遍,更深入理解和掌握epoll事件处理相关知识 ...
最新文章
- 一张图搞定SDF的概念
- CentOS离线安装gcc环境(附安装包+图文并茂)
- NO3 cat-xargs-cp-mv-rm-find命令
- git 使用http方式的一个小问题
- 三度其三——矢量场的旋度
- android sharedpreference 清空,Android 从SharedPreferences中存储,检索,删除和清除数据...
- RESTful源码笔记之RESTful Framework的基本组件
- 平面设计需要学习哪些内容?
- 计算机路由器无线级联配置,不同品牌无线路由器 无线级联 配置案例
- 人工智能 | ShowMeAI资讯日报 #2022.06.07
- Arduino Uno + PAJ7620U2 实现手势识别控制LED灯工作
- 用IOS苹果手机看epub电子书用什么阅读软件好?
- thinkphp5配置完成后,遇到禁止访问!
- 三类医疗器械经营许可证
- python爬虫携程酒店_携程酒店爬取分享
- 【OBS】解决OBS推两个rtmp流 + 带时间戳问题
- 如何测试UDP端口连通性
- c++输出Hello world
- 研发质量管理---(1)质量管理总结
- 常说的软件声卡指的是软件吗?