參考https://blog.csdn.net/yangshangwei/article/details/78157834#spel表達式
在項目中遇到需要根據部分參數來生成緩存key.配置如下:
@Cacheable(key="'selectprovincebyprimarykey_' + #provinceid")
注意在雙引號中常量string是用單引號括起來的。
1.其它key是使用自定義的類來生成key
import java.lang.reflect.Method;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.cache.interceptor.KeyGenerator;
public class KeyGeneratorService implements KeyGenerator {
protected final Logger logger = Logger.getLogger(this.getClass());
@Override
public Object generate(Object target, Method method, Object... params) {
String key = method.getName().toLowerCase() + "_" + StringUtils.join(params, "_");
logger.debug("KEY:" + key);
return key;
}
public static void main(String[] args) {
}
}
2.配置緩存驅動如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean id="KeyGeneratorService" class="com.xxx.xxx.service.KeyGeneratorService" />
<cache:annotation-driven key-generator="KeyGeneratorService" />
<!-- spring自己的換管理器,這裏定義了兩個緩存位置名稱 ,既註解中的value -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="default" />
<bean
class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="config" />
<bean
</property>
</bean>
</beans>