package com.example.demo.RedisPubSubAndListener;
import redis.clients.jedis.JedisPubSub;
public class PubSubScriber extends JedisPubSub {
//订阅消息的处理类
@Override
public void onMessage(String channel, String message) { //收到消息会调用
System.out.println(String.format("receive redis published message, channel %s, message %s", channel, message));
}
@Override
public void onSubscribe(String channel, int subscribedChannels) { //订阅了频道会调用
System.out.println(String.format("subscribe redis channel success, channel %s, subscribedChannels %d",
channel, subscribedChannels));
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) { //取消订阅 会调用
System.out.println(String.format("unsubscribe redis channel, channel %s, subscribedChannels %d",
channel, subscribedChannels));
}
}
package com.example.demo.RedisPubSubAndListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
//发布消息
@RestController
@RequestMapping("/redis")
public class PubRedisController {
@Resource
private StringRedisTemplate strRedisTemplate;
@RequestMapping("/pub")
public String pubMessage() {
strRedisTemplate.convertAndSend("pub_test","heheheh");
System.out.println("pub test");
return "success";
}
}
package com.example.demo.RedisPubSubAndListener;
import redis.clients.jedis.Jedis;
public class SubThread extends Thread{
private Jedis jedis = new Jedis("10.7.8.3",6379);
{
jedis.auth("redisqa");
}
@Override
public void run() {
//订阅主题
jedis.subscribe(new PubSubScriber(),"channel");
}
}
在redis.conf 添加配置:notify-keyspace-events "Ex" //过期时间监听生效
监测键的过期时间: 监测键值
__keyevent@0__:expired