Redis过期key删除监听

监听配置

/**
 * 监听配置
 * 此外redis的配置文件加上:notify-keyspace-events Ex
 */
@Configuration
@Slf4j
public class PubsubConfiguration {

    @Autowired
    private RedisProperties redisProperties;
    @Autowired
    private RedisLister redisLister;

    @Bean
    public ChannelTopic expiredTopic() {
        // __keyevent@0__:expired
        String channelTopic = String.format("__keyevent@%d__:expired", redisProperties.getDatabase());
        log.info("redis key过期监听channel:{}", channelTopic);
        return new ChannelTopic(channelTopic);

    }
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(@Autowired RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.addMessageListener(redisLister, expiredTopic());
        return redisMessageListenerContainer;
    }
}

监听消费:

@Slf4j
@Component
public class RedisLister implements MessageListener {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        log.info("检测到过期的key:{}", key);
        if (key.contains("delete")) {
            ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setNameFormat("线程-%d");
            ThreadFactory factory = threadFactory.build();
            ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                    Runtime.getRuntime().availableProcessors(),
                    Runtime.getRuntime().availableProcessors(),
                    0L,
                    TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1024),
                    factory,
                    new ThreadPoolExecutor.AbortPolicy()
            );
            executorService.execute(() -> doSomething(key));
        }
    }

    private void doSomething(String k) {
        log.info("监听到有过期任务,执行业务...");
    }

}

测试类:

@Slf4j
@RestController
@RequestMapping("/redisLister")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/test")
    public String testLister() {
        Map hashMap = Maps.newHashMap();
        hashMap.put("1", 1);
        hashMap.put("2", 2);
        redisTemplate.boundValueOps("delete").set(hashMap);
        redisTemplate.boundValueOps("savedelete").set(hashMap);
        log.info("redis数据存入成功");
        Boolean delete = redisTemplate.expire("delete", 30, TimeUnit.SECONDS);
        Boolean savedelete = redisTemplate.expire("savedelete", 30, TimeUnit.SECONDS);
        log.info("过期任务创建是否成功:{}", delete);
        log.info("过期任务创建是否成功:{}", savedelete);
        return delete.toString();
    }

}
Last modification:April 13th, 2020 at 05:37 pm