spring CacheManager 对细粒度参数配置的支持, 每个cache执行不同的策略

guavaCache CaffeineCache 默认支持每个cahce 细粒度的参数配置, 不同的cache 不同的配置

spring 的 GuavaCacheManager 和 CaffeineCachaManager 是不支持每个cache不同的细粒度参数配置的, 需要重写CacheManager

增加 cacheSpec 和 defaultSpec. cacheSpec是每个cache的配置, defaultSpec是默认的cache配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14

private Map<String, CacheBuilderSpec> cacheSpec = Maps.newHashMap();

private CacheBuilderSpec defaultSpec = CacheBuilderSpec.parse("expireAfterWrite=1d");

public void setCacheSpec(Map<String, String> cacheSpecString) {
if (MapUtils.isNotEmpty(cacheSpecString)) {
HashMap<String, CacheBuilderSpec> cacheSpecification = Maps.newHashMap();
for (Map.Entry<String, String> en : cacheSpecString.entrySet()) {
cacheSpecification.put(en.getKey(), CacheBuilderSpec.parse(en.getValue()));
}
this.cacheSpec = cacheSpecification;
}
}

重写 createNativeGuavaCache, 以guavaCache 为例, 如果该cache存在配置, 取该cache的配置, 如果没有就取默认配置

1
2
3
4
5
6
7
8
9
10
11
12

/**
* Create a native Guava Cache instance for the specified cache name.
*
* @param name the name of the cache
* @return the native Guava Cache instance
*/
protected com.google.common.cache.Cache<Object, Object> createNativeGuavaCache(final String name) {
CacheBuilderSpec spec = cacheSpec.get(name);
final com.google.common.cache.Cache<Object, Object> cache = CacheBuilder.from(spec == null ? defaultSpec : spec).recordStats().build();
return cache;
}

然后使用以下配置就可以了, 包名这里涉及到公司信息, 省略不计

1
2
3
4
5
6
7
8
9
10
11
12

<cache:annotation-driven cache-manager="cacheManager"/>

<bean id="cacheManager" class="com.*.*.*.*.cache.GuavaCacheManager">
<property name="cacheSpec">
<map>
<entry key="KEY1" value="expireAfterWrite=10m"/>
<entry key="KEY2" value="expireAfterWrite=10m"/>
<entry key="KEY3" value="expireAfterWrite=10m"/>
</map>
</property>
</bean>

也可以使用java bean的配置, 这里不赘述