Spring boot 实现监听 Redis key 失效事件

时间:2024-02-23 21:29:35

定义监听器 实现KeyExpirationEventMessageListener接口
查看源码发现,该接口监听所有db的过期事件keyevent@*:expired"
定义Status1ExpirationListener监听状态1到期

@Slf4j
@Component
public class Status1ExpirationListener extends KeyExpirationEventMessageListener {

	public Status1ExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public void onMessage(Message message, byte[] pattern) {
		// message.toString()可以获取失效的key
		String expiredKey = message.toString();
		// 业务处理
	}

}

定义Status2ExpirationListener监听状态2到期

@Slf4j
@Component
public class Status2ExpirationListener extends KeyExpirationEventMessageListener {

	public Status2ExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}

	@Override
	public void onMessage(Message message, byte[] pattern) {
		// message.toString()可以获取失效的key
		String expiredKey = message.toString();
		// 业务处理
	}

}