package org.jeecg.modules.redis;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.adweb.dmp.service.impl.GACountryReportServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.*;

import java.time.Duration;
import java.util.Date;

/**
 * 支持在{@link Cacheable#cacheNames()}中设置Redis TTL，以#分隔，单位为秒
 *
 * <p>示例: @Cacheable(cacheManager = CacheConfig.TTL_CACHE_MANAGER, cacheNames = "test:demo#3600")
 *
 * <p>用法参考{@link GACountryReportServiceImpl#getCountryStats(String, Date, Date)}方法
 *
 * @author wfansh
 */
@Slf4j
public class TTLCacheManager extends RedisCacheManager {

    public static final char TTL_SPLITTER = '#';

    public TTLCacheManager(
            RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfiguration) {
        super(cacheWriter, cacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfiguration) {
        final int idx = StringUtils.lastIndexOf(name, TTL_SPLITTER);
        if (idx > -1) {
            long ttl = Long.parseLong(StringUtils.substring(name, idx + 1));
            name = StringUtils.substring(name, 0, idx);

            // 设置TTL
            cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(ttl));
        }

        return super.createRedisCache(name, cacheConfiguration);
    }
}
