package com.muyu.event.redis;

import com.alibaba.fastjson.JSON;
import com.muyu.event.common.Fault;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * RedisKeyExpirationListener
 *
 * @author Yangle
 * Date 2024/6/21 14:12
 */
@Log4j2
@Configuration
public class RedisKeyExpirationListener  extends KeyExpirationEventMessageListener {

        @Autowired
        private RabbitTemplate rabbitTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message 失效的key
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {

            String key = message.toString();
            log.info("过期redis数据：" + key);
            Fault fault = Fault.builder()
                    .vin(key)
                    .endTime(new Date())
                    .build();
            rabbitTemplate.convertAndSend("exchange_breakdown","resolve_time", JSON.toJSONString(fault));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
