SpringBoot监听Redis

Redis配置-RedisConfiguration

RedisConfiguration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import com.ruoyi.framework.websocket.RedisKeyListener;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
@EnableCaching
public class RedisConfig{
@Resource
private RedisConnectionFactory factory;

@Resource
private RedisKeyListener listener;

@Bean
public RedisMessageListenerContainer container() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(factory);

//监听所有的key的set事件
// container.addMessageListener(listener, listener.getTopicSet());
//监听所有key的删除事件
container.addMessageListener(listener, listener.getTopicDelete());
//监听所有key的过期事件
container.addMessageListener(listener, listener.getTopicExpired());

return container;
}
}

监听主题-RedisKeyListener

RedisKeyListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import com.ruoyi.common.constant.CacheConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyListener implements MessageListener {

private static final Logger LOGGER = LoggerFactory.getLogger(RedisKeyListener.class);

//监听主题
private final PatternTopic topicExpired = new PatternTopic("__keyevent@*__:expired");

// 删除
private final PatternTopic topicDelete = new PatternTopic("__keyevent@*__:del");

//监听新增、修改主题
private final PatternTopic topicSet = new PatternTopic("__keyevent@*__:set");


@Override
public void onMessage(Message message, byte[] pattern) {
String key = message.toString();
LOGGER.info("message.getBody():{}\nmessage.getChannel():{}, pattern:{}, key:{}",
new String(message.getBody()), new String(message.getChannel()), new String(pattern), key);
}

public PatternTopic getTopicExpired() {
return topicExpired;
}

public PatternTopic getTopicDelete() {
return topicDelete;
}

public PatternTopic getTopicSet() {
return topicSet;
}
}

评论