package com.kcim.common.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;

/**
 * @program: CostAccount
 * @description: redis配置
 * @author: Wang.YS
 * @create: 2023-09-19 15:49
 **/

public class RedisProcessor extends RedisCacheManager {
    /**
     * 默认父类构造方法
     *
     * @param cacheWriter               must not be {@literal null}.
     * @param defaultCacheConfiguration must not be {@literal null}. Maybe just use
     *                                  {@link RedisCacheConfiguration#defaultCacheConfig()}.
     */
    public RedisProcessor(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /**
     * Configuration hook for creating {@link RedisCache} with given name and {@code cacheConfig}.
     * 配置自定义的创建redisCache
     *
     * @param name        must not be {@literal null}.
     *                    这里规定name格式必须为
     *                    <p>
     *                    user#60或者user,#后代表过期时间单位分钟，如果不存在默认一个小时的过期时间
     *                    </p>
     *                    // TODO 2021-9-14 14:19:15 暂未配置一个缓存多个名称的处理 所以暂定该项目缓存使用单命名方式，可以为每个缓存时间加上一个随机时间 防止同事失效造成缓存雪崩
     * @param cacheConfig can be {@literal null}.
     * @return never {@literal null}.
     */
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {

        String[] array = StrUtil.splitToArray(name, "#");
        name = array[0];
        cacheConfig = cacheConfig.entryTtl(Duration.ofMinutes(60));
        if (array.length > 1) {
            long ttl = Long.parseLong(array[1]);
            cacheConfig = cacheConfig.entryTtl(Duration.ofMinutes(ttl));
        }
        return super.createRedisCache(name, cacheConfig);
    }

}
