Spring-Cache key設(shè)置注意事項

為了提升項目的并發(fā)性能,考慮引入本地內(nèi)存Cache,對:外部數(shù)據(jù)源訪問、Restful API調(diào)用、可重用的復(fù)雜計算 等3種類型的函數(shù)處理結(jié)果進行緩存。目前采用的是Spring Cache的@Cacheable注解方式,緩存具體實現(xiàn)選取的是Guava Cache。

具體緩存的配置此處不再介紹,重點對于key的配置進行說明:

1、基本形式

@Cacheable(value="cacheName", key"#id")

public ResultDTO method(int id);

2、組合形式

@Cacheable(value="cacheName", key"T(String).valueOf(#name).concat('-').concat(#password))

public ResultDTO method(int name, String password);

3、對象形式

@Cacheable(value="cacheName", key"#user.id)

public ResultDTO method(User user);

4、自定義Key生成器

@Cacheable(value="gomeo2oCache", keyGenerator = "keyGenerator")

public ResultDTO method(User user);

有一個尤其需要注意的坑:Spring默認的SimpleKeyGenerator是不會將函數(shù)名組合進key中的

舉個栗子:

@Component

? ? public class CacheTestImpl implements CacheTest {

? ? ? ? @Cacheable("databaseCache")

? ? ? ? public Long test1()

? ? ? ? { return 1L; }

? ? ? ? @Cacheable("databaseCache")

? ? ? ? public Long test2()

? ? ? ? { return 2L; }

? ? ? ? @Cacheable("databaseCache")

? ? ? ? public Long test3()

? ? ? ? { return 3L; }

? ? ? ? @Cacheable("databaseCache")

? ? ? ? public String test4()

? ? ? ? { return "4"; }

? ? }

我們期望的輸出是:

1

2

3

4

而實際上的輸出是:

1

1

1

ClassCastException: java.lang.Long cannot be cast to java.lang.String

此外,原子類型的數(shù)組,直接作為key使用也是不會生效的

為了解決上述2個問題,自定義了一個KeyGenerator如下:

class CacheKeyGenerator implements KeyGenerator {

? ? // custom cache key

? ? public static final int NO_PARAM_KEY = 0;

? ? public static final int NULL_PARAM_KEY = 53;


? ? @Override

? ? public Object generate(Object target, Method method, Object... params) {

? ? ? ? StringBuilder key = new StringBuilder();

? ? ? ? key.append(target.getClass().getSimpleName()).append(".").append(method.getName()).append(":");

? ? ? ? if (params.length == 0) {

? ? ? ? ? ? return key.append(NO_PARAM_KEY).toString();

? ? ? ? }

? ? ? ? for (Object param : params) {

? ? ? ? ? ? if (param == null) {

? ? ? ? ? ? ? ? log.warn("input null param for Spring cache, use default key={}", NULL_PARAM_KEY);

? ? ? ? ? ? ? ? key.append(NULL_PARAM_KEY);

? ? ? ? ? ? } else if (ClassUtils.isPrimitiveArray(param.getClass())) {

? ? ? ? ? ? ? ? int length = Array.getLength(param);

? ? ? ? ? ? ? ? for (int i = 0; i < length; i++) {

? ? ? ? ? ? ? ? ? ? key.append(Array.get(param, i));

? ? ? ? ? ? ? ? ? ? key.append(',');

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } else if (ClassUtils.isPrimitiveOrWrapper(param.getClass()) || param instanceof String) {

? ? ? ? ? ? ? ? key.append(param);

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? log.warn("Using an object as a cache key may lead to unexpected results. " +

? ? ? ? ? ? ? ? ? ? ? ? "Either use @Cacheable(key=..) or implement CacheKey. Method is " + target.getClass() + "#" + method.getName());

? ? ? ? ? ? ? ? key.append(param.hashCode());

? ? ? ? ? ? }

? ? ? ? ? ? key.append('-');

? ? ? ? }

? ? ? ? String finalKey = key.toString();

? ? ? ? long cacheKeyHash = Hashing.murmur3_128().hashString(finalKey, Charset.defaultCharset()).asLong();

? ? ? ? log.debug("using cache key={} hashCode={}", finalKey, cacheKeyHash);

? ? ? ? return key.toString();

? ? }

}

采用此方式后可以解決:多參數(shù)、原子類型數(shù)組、方法名識別 等問題

原文:https://blog.csdn.net/syani/article/details/52239967

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容