package cn.reghao.bnt.web.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

/**
 * 缓存配置
 *
 * @author reghao
 * @date 2023-05-22 16:31:04
 */
@EnableCaching
@Configuration
public class CacheConfig {
    /**
     * 由 spring cache 管理的缓存
     *
     * @param
     * @return
     * @date 2025-09-23 17:32:23
     */
    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        Caffeine<Object, Object> caffeineCache = Caffeine.newBuilder()
                .initialCapacity(1000)
                .maximumSize(10_000)
                .expireAfterAccess(365, TimeUnit.DAYS);
        cacheManager.setCaffeine(caffeineCache);
        return cacheManager;
    }

    /**
     * 一个独立的 cache bean
     *
     * @param
     * @return
     * @date 2025-09-23 17:32:41
     */
    @Bean
    public Cache<String, Object> caffeineCache() {
        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(30, TimeUnit.DAYS)
                // 初始的缓存空间大小
                .initialCapacity(10_000)
                // 缓存的最大条数
                .maximumSize(100_000)
                .recordStats()
                .build();
    }
}
