参考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>