MultiLevelCacheManager.java
1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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();
}
}