我想用KeyExpirationEventMessageListener监听过期事件,但我找不到一个例子。
有人知道如何使用Spring boot 1.4.3& amp; Spring Data Redis?
我目前正在做这个
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");
我想直接使用Spring而不是Jedis。
此致
答案 0 :(得分:5)
请勿KeyExpirationEventMessageListener
使用RedisKeyExpiredEvent
,因为它会触发RedisKeyValueAdapter.onApplicationEvent
,导致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
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase
// Otherwise I have a NullPointer, don't know why
@TestPropertySource(
properties = {"management.health.mail.enabled=false"})
public class MailServiceTest extends CommonServiceTest {
在自己的主题上运行所有通知。