package com.czg.config;

import com.czg.order.service.OrderInfoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * redis key过期监听
 *
 * @author ww
 */
@Slf4j
@Configuration
public class RedisKeyExpirationListener implements MessageListener {

    @Value("${spring.data.redis.database}")
    private String database;
    @Resource
    private OrderInfoService tbOrderInfoService;


    //redis key失效监听
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        // 监听特定键的过期事件
        container.addMessageListener(this, new PatternTopic("__keyevent@" + database + "__:expired"));
        return container;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());

        // 检查过期的键是否以特定前缀开头
        if (expiredKey.startsWith(RedisCst.classKeyExpired.EXPIRED_ORDER)) {
            log.info("监听到订单过期,订单Id: {}", expiredKey);
            String orderId = expiredKey.substring(RedisCst.classKeyExpired.EXPIRED_ORDER.length());
            tbOrderInfoService.expired(Long.parseLong(orderId));
        }
    }
}
