缓存(六)key的生成策略

1.默认使用keyGenerator生成:默认使用simpleKeyGennerator生成key:
       simpleKeyGennerator默认如果没有参数:key = new SimpleKey()
                                                          一个参数:key = 参数值    
                                                        多个参数:key = new SimpleKey(params)    

2.可以用SpEL表达式去写key,可以实现动态拼接key,key="#root.methodName+'['+#参数属性名+']'"会被拼接为方法名【参数】。
 
3.也可以自定义一个key生成器
 
package com.config;

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.util.Arrays;

@Configuration
public class MyCacheConfig {


    @Bean(name = "myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+Arrays.asList(params).toString() +"]";
            }
        };
    }
}
调用的时候:
    @Cacheable(cacheNames = "users",keyGenerator = "myKeyGenerator")

 

 
posted @ 2019-07-13 14:16  TangXinPing  阅读(3865)  评论(0编辑  收藏  举报