正文
Springboot集成cache的key生成策略
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
代码接上文:深度理解springboot集成redis缓存之源码解析
## 1.使用SpEL表达式
@Cacheable(cacheNames = "emp",key = "#root.methodName+'['+#id+']'")
public Employee getEmp(Integer id) {
System.out.println("查询"+id+"号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
@Cacheable(cacheNames = "emp",key = "#root.methodName+'['+#id+']'")
public Employee getEmp(Integer id) {
System.out.println("查询"+id+"号员工");
Employee emp = employeeMapper.getEmpById(id);
return emp;
}
}
debug模式下运行查看key的结果
这样key的名字就换成我们自定义的了
2.自定义key生成策略
@Configuration
public class MyCacheConfig {
@Bean("myKey")
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
@Override
public Object generate(Object target, Method method, Object... params) {
return method.getName()+"["+ Arrays.asList(params).toString()+"]";
}
};
}
}
@Configuration
public class MyCacheConfig {
@Bean("myKey")
public KeyGenerator keyGenerator(){
return new KeyGenerator(){
@Override
public Object generate(Object target, Method method, Object... params) {
return method.getName()+"["+ Arrays.asList(params).toString()+"]";
}
};
}
}
结果依然是如此