package com.docus.server.common.util;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * redis 键过期监听
 *
 * @author wyb
 */
public class RedisKeyExpirationListener implements MessageListener {
    private final StringRedisTemplate stringRedisTemplate;
    private final List<RedisKeyExpirationHandler> handlers = new CopyOnWriteArrayList<>();

    public RedisKeyExpirationListener(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] body = message.getBody();
        String expireRedisKey = stringRedisTemplate.getStringSerializer().deserialize(body);
        for (RedisKeyExpirationHandler handler : handlers) {
            handler.handle(expireRedisKey);
        }
    }
    /**
     * 注册redisKey过期的处理器
     *
     * @param handler redisKey过期的处理器
     */
    public void register(RedisKeyExpirationHandler handler) {
        Objects.requireNonNull(handler);
        handlers.add(handler);
    }
}
