接口KeyGenerator
要實現自定義,要實現spring提供的接口KeyGenerator
package org.springframework.cache.interceptor;
helper
- fastjson
public class JsonHelper {
/**
* Java對象序列化為JSON字符串
*
* @param obj Java對象
* @return json字符串
*/
public static String toJson(Object obj) {
return JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
}
}
- beanHelper
package com.ghgcn.mysb.chapter03.helper;
import org.springframework.util.ClassUtils;
import java.net.URI;
import java.net.URL;
import java.util.Date;
import java.util.Locale;
public class BeanHelper {
/**
* 判斷是否是簡單值類型.包括:基礎數據類型块饺、CharSequence洞拨、Number欣范、Date沽损、URL巾表、URI袖外、Locale史隆、Class;
*
* @param clazz
* @return
*/
public static boolean isSimpleValueType(Class<?> clazz) {
return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() || CharSequence.class.isAssignableFrom(clazz)
|| Number.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz) || URI.class == clazz
|| URL.class == clazz || Locale.class == clazz || Class.class == clazz);
}
}
SpringCacheKeyGenerator
package com.ghgcn.mysb.chapter03.support;
import com.ghgcn.mysb.chapter03.helper.BeanHelper;
import com.ghgcn.mysb.chapter03.helper.JsonHelper;
import org.springframework.cache.interceptor.KeyGenerator;
import java.lang.reflect.Method;
@Component //標記為組件
public class SpringCacheKeyGenerator implements KeyGenerator {
private final static int NO_PARAM_KEY = 0;
private String keyPrefix = "jf";// key前綴,用于區(qū)分不同項目的緩存曼验,建議每個項目單獨設置
@Override
public Object generate(Object target, Method method, Object... params) {
char sp = ':';
StringBuilder strBuilder = new StringBuilder(30);
strBuilder.append(keyPrefix);
strBuilder.append(sp);
// 類名
strBuilder.append(target.getClass().getSimpleName());
strBuilder.append(sp);
// 方法名
strBuilder.append(method.getName());
strBuilder.append(sp);
if (params.length > 0) {
// 參數值
for (Object object : params) {
if (BeanHelper.isSimpleValueType(object.getClass())) {
strBuilder.append(object);
} else {
strBuilder.append(JsonHelper.toJson(object).hashCode());
}
}
} else {
strBuilder.append(NO_PARAM_KEY);
}
return strBuilder.toString();
}
public String getKeyPrefix() {
return keyPrefix;
}
public void setKeyPrefix(String keyPrefix) {
this.keyPrefix = keyPrefix;
}
}