集群下的redis过期监听

集群下的redis过期监听

转载:https://blog.csdn.net/xuyide6/article/details/86686152
修改redis.conf中的notify-keyspace-events “Ex”,再建监听类来监听这一事件
话不多说直接上代码
1.配置pom文件


            org.springframework.boot
            spring-boot-starter-data-redis
            2.0.2.RELEASE
        

2.配置yml文件

spring:
  redis:
    password: ******
    expireSeconds: 120
    commandTimeout: 10000
    sub:
      clusterAddress: redis://192.168.40.207:8001
    cluster:
      max-redirects: 100
      nodes: 192.168.40.207:8001,192.168.40.207:8002,192.168.40.208:8001,192.168.40.208:8002,192.168.40.209:8001,192.168.40.209:8002

3.redis配置

@Configuration
public class RedisListenerConfig {

    @Value("${spring.redis.sub.clusterAddress}")
    private String redisSubURI;

    @Value("${spring.redis.password}")
    private String redisPassword;

    @Bean(destroyMethod = "shutdown")
    ClientResources clientResources() {
        return DefaultClientResources.create();
    }

    @Bean(destroyMethod = "shutdown")
    RedisClusterClient redisClusterClient(ClientResources clientResources) {

        RedisURI redisURI = RedisURI.create(redisSubURI);
        redisURI.setPassword(redisPassword);
        return RedisClusterClient.create(clientResources, redisURI);
    }

    @Bean(destroyMethod = "close")
    StatefulRedisClusterConnection statefulRedisClusterConnection(RedisClusterClient redisClusterClient) {
        return redisClusterClient.connect();
    }
}

4.创建监听
@Slf4j用的是lombok插件注解,不用可以去掉

@Component
@Slf4j
public class RedisClusterListener extends RedisClusterPubSubAdapter {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void message(RedisClusterNode node, Object channel, Object message) {
        String expireKey = null;
        try {
            //自己的业务逻辑
           expireKey = (String) message;
           System.out.println("监听到key:"+expireKey);
        }catch (Exception e){
            log.error("消息转换失败");
            return;
        }
    }
}

5.创建订阅者同时启动监听

@Component
public class RedisSubscriber extends RedisPubSubAdapter implements ApplicationRunner {

    private static final String EXPIRED_CHANNEL = "__keyevent@0__:expired";

    @Autowired
    private RedisClusterListener redisClusterListener;

    @Autowired
    private RedisClusterClient redisClusterClient;

    public void startListener(){
        StatefulRedisClusterPubSubConnection pubSubConnection = redisClusterClient.connectPubSub();
        pubSubConnection.setNodeMessagePropagation(true);
        pubSubConnection.addListener(redisClusterListener);

        PubSubAsyncNodeSelection masters = pubSubConnection.async().masters();
        NodeSelectionPubSubAsyncCommands commands = masters.commands();
        commands.subscribe(EXPIRED_CHANNEL);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        startListener();
    }
}

你可能感兴趣的:(集群下的redis过期监听)