package com.ssyf.plugs.cache;

import com.ssyf.plugs.cache.customs.CustomRedisMessageListener;
import com.ssyf.plugs.cache.properties.CacheProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 缓存监听器
 * @author huwei
 * @date 2022/11/27 13:28
 */
@Component
public class RedisCacheMessageListener implements MessageListener , CustomRedisMessageListener {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AdaptCacheManager multiCacheManager;

    @Autowired
    private CacheProperties cacheProperties;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //处理收到的消息，去清除其他多级缓存的一级缓存
        CacheMessage cacheMessage = (CacheMessage) redisTemplate.getValueSerializer().deserialize(message.toString().getBytes());

        //清除本地缓存
        multiCacheManager.clearLocal(cacheMessage.getName(), cacheMessage.getKey(), cacheMessage.getUniqueKey());
    }

    @Override
    public List<String> topics() {
        return Collections.singletonList(cacheProperties.getTopic());
    }

    @Override
    public MessageListener listener() {
        return this;
    }
}
