查找了一些后总结,个人食用。
1.导包
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置类RedisConfig
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory connectionFactory;
@Bean
RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//container.addMessageListener(new RedisExpiredListener(), new PatternTopic("__keyevent@0__:expired"));
return container;
}
// 创建基本的key监听器
/* */
@Bean
public RedisKeyChangeListener redisKeyChangeListener() throws Exception {
RedisKeyChangeListener listener = new RedisKeyChangeListener(redisMessageListenerContainer(),"");
return listener;
}
}
3.配置监听器
/**
* @description 期望是可以监听某个key的变化,而不是失效
*/
public class RedisKeyChangeListener implements MessageListener/* extends KeyspaceEventMessageListener */ {
private final String listenerKeyName; // 监听的key的名称
private static final Topic TOPIC_ALL_KEYEVENTS = new PatternTopic("__keyevent@*"); //表示只监听所有的key
private static final Topic TOPIC_KEYEVENTS_SET = new PatternTopic("__keyevent@0__:set"); //表示只监听所有的key
private static final Topic TOPIC_KEYNAMESPACE_NAME = new PatternTopic("__keyspace@0__:myKey"); // 不生效
// 监控
//private static final Topic TOPIC_KEYEVENTS_NAME_SET_USELESS = new PatternTopic("__keyevent@0__:set myKey");
private String keyspaceNotificationsConfigParameter = "KEA";
public RedisKeyChangeListener(RedisMessageListenerContainer listenerContainer, String listenerKeyName) {
this.listenerKeyName = listenerKeyName;
initAndSetRedisConfig(listenerContainer);
}
public void initAndSetRedisConfig(RedisMessageListenerContainer listenerContainer) {
if (StringUtils.hasText(keyspaceNotificationsConfigParameter)) {
RedisConnection connection = listenerContainer.getConnectionFactory().getConnection();
try {
Properties config = connection.getConfig("notify-keyspace-events");
if (!StringUtils.hasText(config.getProperty("notify-keyspace-events"))) {
connection.setConfig("notify-keyspace-events", keyspaceNotificationsConfigParameter);
}
} finally {
connection.close();
}
}
// 注册消息监听
listenerContainer.addMessageListener(this, TOPIC_ALL_KEYEVENTS);
}
@Reference
private UserInfoApi userInfoApi;
@Reference
private FreezeApi freezeApi;
@Override
public void onMessage(Message message, byte[] pattern) {
String key = new String(message.getBody());
String method = new String(message.getChannel());
System.out.println(key + "----" + method);
}
}