springBoot项目监听redis中间件key变化
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
@Configuration
public class RedisListenerConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Autowired
private RedisProperties redisProperties;
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
return container;
}
@Bean
public RedisKeyChangeListener redisKeyChangeListener() {
return new RedisKeyChangeListener(redisMessageListenerContainer());
}
@Slf4j
public static class RedisKeyChangeListener implements MessageListener {
/**
* KEA 指配置的模式
*/
private String keyspaceNotificationsConfigParameter = "KEA";
public RedisKeyChangeListener(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();
}
}
// 监听规则
// new PatternTopic("__keyevent@*") 监听 整个redis数据库 的所有事件
// new PatternTopic("__keyevent@0__:set") 监听 redis 0号数据库 的所有 set 事件
// new PatternTopic("__keyspace@7__:myKey*") 监听 redis 7号数据库 中键名为 myKey开头的 所有事件
listenerContainer.addMessageListener(this, new PatternTopic("__keyspace@7__:incar*"));
}
@Override
public void onMessage(Message message, byte[] pattern) {
log.info("key发生变化类型:[ {} ],key监听正则:[ {} ],变化key:[ {} ]", message, new String(pattern, StandardCharsets.UTF_8), new String(message.getChannel(), StandardCharsets.UTF_8));
}
}
}
参考:
分类:
java
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了