I would like to listen expiration events with KeyExpirationEventMessageListener but I can't find an example.
Someone know how to do it using Spring boot 1.4.3 & Spring Data Redis?
I am currently doing this
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
this.jedis = pool.getResource();
this.jedis.psubscribe(new JedisPubSub() {
@Override
public void onPMessage(String pattern, String channel, String message) {
System.out.println("onPMessage pattern " + pattern + " " + channel + " " + message);
List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForValue().get("val:" + message);
operations.delete("val:" + message);
return operations.exec();
}
});
System.out.println(txResults.get(0));
}
}, "__keyevent@0__:expired");
And I would like to use Spring instead of Jedis directly.
Regards
Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.
Once configured, the template is thread-safe and can be reused across multiple instances. Out of the box, RedisTemplate uses a Java-based serializer for most of its operations.
Helper class that simplifies Redis data access code. Performs automatic serialization/deserialization between the given objects and the underlying binary data in the Redis store. By default, it uses Java serialization for its objects (through JdkSerializationRedisSerializer ).
In spring boot you need to set spring. cache. type=redis and this would create your cache using Redis. @Autowired RedisTemplate<String, String> redisTemplate; redisTemplate.
Don't use KeyExpirationEventMessageListener
as it triggers RedisKeyExpiredEvent
which then leads to a failure in RedisKeyValueAdapter.onApplicationEvent
.
Rather use RedisMessageListenerContainer
:
@Bean
RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
listenerContainer.addMessageListener((message, pattern) -> {
// event handling comes here
}, new PatternTopic("__keyevent@*__:expired"));
return listenerContainer;
}
RedisMessageListenerContainer
runs all notifications on an own thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With