Spring Data Redis实现超时通知

Spring Data Redis实现超时通知

参考:【springmvc订阅redis键过期消息通知】-- https://blog.csdn.net/u012930316/article/details/78587865

Spring Data Redis实现Redis键值延迟通知是结合【Spring Data Redis实现订阅与发布】和【Redis超时触发事件】实现的。

1、修改spring-redis,xml
2、监听器程序
3、启动订阅
4、测试类
5、运行结果

1、修改spring-redis.xml
配置消息监听器

配置监听模式/频道
Spring Data Redis实现超时通知_第1张图片
2、监听器程序
public class MyRedisKeyExpiredMessageDelegate implements MessageListener {

	public void onMessage(Message message, byte[] pattern) {  
        System.out.println("channel:" + new String(message.getChannel())  
                + ",message:" + new String(message.getBody()));  
    } 
	
}
3、启动订阅
public class SubMain {

	public static void main(String[] args) {
        new ClassPathXmlApplicationContext("spring-pool.xml","spring-redis.xml");
        while (true) { //这里是一个死循环,目的就是让进程不退出,用于接收发布的消息
            try {
                System.out.println("current time: " + new Date());
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
4、测试类
缓存一个键值,并设置失效时间
public class PubMain {

	private RedisUtil redisUtil;
	
	@Before
	public void before() {
        
		ApplicationContext ac = new ClassPathXmlApplicationContext("spring-pool.xml","spring-redis.xml");
        
		redisUtil = (RedisUtil)ac.getBean("redisUtil", RedisUtil.class);
	}
	
	@Test
    public void testPublishMessage() throws Exception {
        
		redisUtil.set("ggg", "ggg-1234", 10L);
    }
}
5、运行结果
先运行启动订阅程序
Spring Data Redis实现超时通知_第2张图片
启动测试类:
Spring Data Redis实现超时通知_第3张图片

你可能感兴趣的:(Redis,Java)