Redis Key 过期事件监听

目的是为了实现定时推送,又不想写定时任务扫

1、redis 开启key过期通知

修改redis server 配置文件,开启keyt过期听通知配置

notify-keyspace-events Ex

2、 key过期Listener

@Component
public class RedisKeyExpiredListener extends JedisPubSub {

    private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpiredListener.class);

    @Autowired
    private PushMsgService pushMsgService;

    private static final String PREFIX_EVENT_KEY = "xxx:event:sms:";

    @Override
    public void onMessage(String channel, String message) {
        logger.debug("redis event key :{}", message);
        if (message.startsWith(PREFIX_EVENT_KEY)) {
            pushMsgService.pushSmsForSms(Long.parseLong(message.substring(message.lastIndexOf(":") + 1)));
        }
    }
}

3、注册redis key过期Listener

@PostConstruct
private void init() {
	// 因为此方法阻塞线程
	new Thread(new Runnable() {
	    @Override
	    public void run() {
		// 订阅redis key过期时间,需要reids 服务器配置notify-keyspace-events Ex
		jedisPool.getResource().subscribe(redisKeyExpiredListener, "__keyevent@2__:expired");
	    }
	}).start();
}

keyevent@2:expired
__keyevent必须以此开头;
@2 表示监听第二个数据库;
:expired 表示过期事件

4、设置过期时间

Jedis jedis = jedisPool.getResource();
jedis.select(2);
jedis.set(PREFIX_EVENT_KEY + teaching.getId(), String.valueOf(teaching.getId()));
jedis.expire(PREFIX_EVENT_KEY + teaching.getId(), expireTime.intValue());

你可能感兴趣的:(Java)