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));
}
}
}
参考:
redis中文文档相关章节
redis官方文档相关章节
SpringBoot:监控Redis中的某个Key的变化(自定义监听器)