java实现redis的键失效回调事件

依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>1.5.10.RELEASE</version>
        </dependency>

配置

# REDIS (RedisProperties)
# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09
spring.redis.database=7
# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=localhost
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=${redis.port}
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=${redis.password}
# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-active=100
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-wait=-1
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.max-idle=10
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.min-idle=0
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=0
spring.data.redis.repositories.enabled=true

配置类


@Configuration
public class RedisConfigForMessageListener {


    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    private RedisMessageListenerContainer redisMessageListenerContainer;




    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }


    @Bean
    public KeyExpiredListenForMessageListener registerListener() {
        redisMessageListenerContainer.setConnectionFactory(connectionFactory);
        KeyExpiredListenForMessageListener listener = new KeyExpiredListenForMessageListener();
        redisMessageListenerContainer.addMessageListener(listener,new PatternTopic("__keyevent@*__:expired"));
        return listener;
    }
}

监听类


public class KeyExpiredListenForMessageListener extends KeyExpirationEventMessageListener {


    public KeyExpiredListenForMessageListener(RedisMessageListenerContainer listenerContainer, RfidManagement rfidManagement, DeviceDao deviceDao,StringRedisTemplate redisTemplate) {
        super(listenerContainer);
        this.rfidManagement = rfidManagement;
        this.deviceDao = deviceDao;
        this.redisTemplate=redisTemplate;
    }


    @Override
    public void onMessage(Message message, byte[] bytes) {
        logger.info("redis key expire,key = {} ", message.toString());
        String expireKey = message.toString();
        //此处可能有乱码有乱码
        
        
    }
   
    

   
}

你可能感兴趣的:(java,redis,开发语言)