MultiLevelCacheManager.java 1.91 KB
package com.infoloop.tianting.cache;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 多级缓存管理器
 * 实现Spring Cache CacheManager接口,桥接到现有的MultiLevelCacheService
 */
@Slf4j
public class MultiLevelCacheManager implements CacheManager {

    private final CacheService cacheService;
    private final CacheProperties cacheProperties;
    private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>();

    public MultiLevelCacheManager(CacheService cacheService, CacheProperties cacheProperties) {
        this.cacheService = cacheService;
        this.cacheProperties = cacheProperties;
        log.info("多级缓存管理器初始化完成,默认TTL: {}s", cacheProperties.getDefaultTtl());
    }

    @Override
    public Cache getCache(String name) {
        if (name == null) {
            return null;
        }
        
        return cacheMap.computeIfAbsent(name, cacheName -> {
            log.debug("创建新的缓存区域: {}", cacheName);
            return new SpringCacheAdapter(cacheName, cacheService, cacheProperties.getDefaultTtl());
        });
    }

    @Override
    public Collection<String> getCacheNames() {
        return cacheMap.keySet();
    }

    /**
     * 清除所有缓存
     */
    public void clearAll() {
        cacheMap.values().forEach(Cache::clear);
        log.info("已清除所有缓存区域");
    }

    /**
     * 获取缓存统计信息
     */
    public String getCacheStats() {
        StringBuilder stats = new StringBuilder();
        stats.append("缓存区域数量: ").append(cacheMap.size()).append("\n");
        stats.append("缓存区域列表: ").append(String.join(", ", getCacheNames()));
        return stats.toString();
    }
}