监听redis过期的key

一:需要监听过期的redis keys

     在redis.conf 里添加 notify-keyspace-events "Ex" ,放到配置参数的最后。

 

二:不需要账号密码访问

     改变redis.conf 里的protected-mode 的属性值为 no

三:去掉绑定的地址

    在redis.conf 里注销掉 bind 127.0.0.1



./redis-service ../redis.conf &


客户端执行redis 命令。
 psubscribe __keyevent@*__:expired 


pubsub配置:

@Configuration
@Import( value = ServiceApplication.class )
public class PubsubConfiguration  {

/*    @Autowired
    private RedisClient redisClient;*/

    @Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter( new RedisMessageListener() );
    }


    @Autowired
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory ) {

        final RedisMessageListenerContainer container =
                new RedisMessageListenerContainer();
        container.setConnectionFactory( connectionFactory );
        container.addMessageListener( messageListener(), new ChannelTopic( "__keyevent@0__:expired" ) );

        return container;
    }

/*    @Bean
    public MessageListener listener() {
        return new RedisMessageListener();
    }*/
}


 springboot 启动类

@SpringBootApplication
@ComponentScan
public class ServiceApplication implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(ServiceApplication.class);

    @Override
    public void run(String... strings) throws Exception {

    }

    public static void main(String[] args) throws Exception {
        ApplicationContext ctx = SpringApplication.run(ServiceApplication.class, args);
        SpringContextUtil.setApplicationContext(ctx);
        logger.info("service start success .....");
    }

}


监听类实现:

public class RedisMessageListener implements MessageListener {

    protected Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    @Autowired
    private BookTableBo bookTableBo;
    @Autowired
    private CalledRecordBo calledRecordBo;

    @Autowired
    private MqService mqService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        try {
            System.out.println( "Message received: " + message.toString() );
            logger.info( "Message received: " + message.toString() );
            if(StringUtils.isNotBlank(key) && key.startsWith(RedisUtils.TABLE_PREFIX)){
                String[] tKey = key.split("_");
                if(tKey.length==7){
                    String traceID = UUID.randomUUID().toString();
                    Integer groupID = Integer.parseInt(tKey[2]);
                    Integer shopID = Integer.parseInt(tKey[3]);
                    long mealDate = Long.parseLong(tKey[4]);
                    Integer mealTimeTypeID = Integer.parseInt(tKey[5]);
                    Integer tableID = Integer.parseInt(tKey[6]);
                    String redisKey = new StringBuilder()
                            .append(groupID)
                            .append("_")
                            .append(shopID)
                            .append("_")
                            .append(mealDate)
                            .append("_")
                            .append(mealTimeTypeID)
                            .toString();
                    if(null == bookTableBo){
                        bookTableBo =(BookTableBo)  SpringContextUtil.getBean("bookTableBo");
                    }
                    if(null == mqService){
                        mqService =(MqService)  SpringContextUtil.getBean("mqService");
                    }
                    DataSourceContextHolder.setDataSourceType(Constants.DB_ROUTEKEY_PREFIX_READ + groupID);
                    List<Integer> userableUnLockTables = bookTableBo.userableUnLockTable(groupID,
                            shopID,
                            tableID,
                            traceID,
                            redisKey,
                            mealDate,
                            mealTimeTypeID);

                    List<MealTimeTableStatusMqVO> mealTimeTableStatusMqBeans = new ArrayList<>();
                    for (Integer one:userableUnLockTables){
                        mealTimeTableStatusMqBeans.add(MqUtils.buildMealTimeTableStatusMqBean(one, OrderStatusEnum.FREE.getStatus(),0L,0L,0,"",0,"",0));
                    }
                    mqService.sendMessToShop(shopID, MqUtils.buildUnTakeUpTableMq(traceID,mealDate,mealTimeTypeID,mealTimeTableStatusMqBeans));
                    mqService.sendTableStatusChangeMq(groupID,shopID,mealDate,mealTimeTypeID,userableUnLockTables,null);
                }
            }
        }catch (Exception e){
            logger.error("handler expire key error"+key,e);
        }
    }
	}

猜你喜欢

转载自blog.csdn.net/zhangxihangzhuan/article/details/80708427