package com.ho.business.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.concurrent.TimeUnit;

/**
 * @author fancl
 * @desc: Caffeine配置类
 * @date 2023/4/14
 */
@Configuration
public class CaffeineConfig extends CaffeineCacheManager{

    //10秒钟的缓存
    @Bean(name = "tenSecondCacheManager")
    @Primary
    public CacheManager tenSecondCacheManager(){
        Caffeine caffeine = Caffeine.newBuilder()
                .initialCapacity(50) //初始大小
                .maximumSize(20000)  //最大大小
                .expireAfterWrite(10 ,TimeUnit.SECONDS); //写入/多久过期

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setAllowNullValues(true);
        caffeineCacheManager.setCaffeine(caffeine);
        return caffeineCacheManager;
    }

    //30秒钟的缓存
    @Bean(name = "thirtySecondCacheManager")
    public CacheManager thirtySecondCacheManager(){
        Caffeine caffeine = Caffeine.newBuilder()
                .initialCapacity(50) //初始大小
                .maximumSize(20000)  //最大大小
                .expireAfterWrite(30 ,TimeUnit.SECONDS); //写入/多久过期

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setAllowNullValues(true);
        caffeineCacheManager.setCaffeine(caffeine);
        return caffeineCacheManager;
    }

    //2分钟的缓存
    @Bean(name = "towMinuteCacheManager")
    public CacheManager towMinuteCacheManager(){
        Caffeine caffeine = Caffeine.newBuilder()
                .initialCapacity(50) //初始大小
                .maximumSize(20000)  //最大大小
                .expireAfterWrite(2, TimeUnit.MINUTES); //写入/多久过期

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setAllowNullValues(true);
        caffeineCacheManager.setCaffeine(caffeine);
        return caffeineCacheManager;
    }

    //5分钟的缓存
    @Bean(name = "fiveMinuteCacheManager")
    public CacheManager fiveMinuteCacheManager(){
        Caffeine caffeine = Caffeine.newBuilder()
                .initialCapacity(50) //初始大小
                .maximumSize(20000)  //最大大小
                .expireAfterWrite(50, TimeUnit.MINUTES); //写入/多久过期

        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setAllowNullValues(true);
        caffeineCacheManager.setCaffeine(caffeine);
        return caffeineCacheManager;
    }


}
