package com.muyu.common.caffeine.bean;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.muyu.common.caffeine.enums.CacheNameEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Caffeine管理器
 * @Author: WangXin
 * @Name: CaffeineCacheConfig
 * @Description: Caffeine管理器
 */

@Slf4j
@Component
public class CaffeineManager {

    /**
     * 创建缓存管理器
     * @return  缓存管理器实例
     */
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        List<String> cacheNames = CacheNameEnums.getCodes();
        cacheManager.setCaches(cacheNames.stream()
                .map(name -> new CaffeineCache(
                        name,
                        Caffeine.newBuilder()
                                .recordStats()
                                .build()))
                .toList());
        log.info("缓存管理器初始化完成,缓存分区:{}", cacheNames);
        return cacheManager;
    }

}
