package com.zhongshu.card.server.core.listener;

import com.zhongshu.card.server.core.service.keyExpire.KeyExpire;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
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;

/**
 * redis 过期的key
 * @author TRX
 * @date 2024/12/23
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private ApplicationContext applicationContext;

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

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取到过期的键
        String expiredKey = message.toString();
        log.info("redis expired: {}", expiredKey);
        this.applicationContext.getBeansOfType(KeyExpire.class).values().forEach(it -> {
            if (it.isAccessKey(expiredKey)) {
                it.handle(expiredKey);
            }
        });
    }
}
