假设一切都已经配置妥当。
Spring缓存注解@Cache,@CachePut , @CacheEvict,@CacheConfig使用的使用方法参照: http://blog.csdn.net/sanjay_f/article/details/47372967
@Cacheable(value=”testcache”,key=”#userName”)
使用的时候 value与key组成了唯一标识来标识一个缓存,key可以不指定。
如果key不指定的话,参数会作为key与value进行组合对应一个缓存。
可以理解为,如果key写死的话,那么这个方法的缓存就确定了,无论传什么值来,返回的都是这个缓存。
如果key不指定,那么每次传不同的参数,value就会与新参数组合为一个新的标识,指向新的缓存。
key也可以指向参数对象中的某个值。
如果参数是一个string 那么key可以不写了
如果参数是一个实体 那么key可以写为实体的id
其实可以理解为,value是一个组,我们可以把一个接口里面的所有value都定义为同一,然后key不同,或者说key以参数加个后缀区分。
这个value与key,如果对应map的话,其实是map中的key 缓存是map中的value
@Cacheable(value= "customLikeName", key="#test")
test为function的参数,String类型
@Cacheable(value= "customLikeName", key="#orgCustom.getId()")
orgCustom为一个实体,非常实用
@Cacheable(value= "customLikeName", key="'jerry'")
key写死,没什么卵用
@Cacheable(value="andCache",key="#userId + 'findById'")
public SystemUser findById(String userId) {
SystemUser user = (SystemUser) dao.findById(SystemUser.class, userId);
return user ;
}
这种写法可以应对key为部分参数的情况
@Cacheable(value = CacheConstant.newsCache)
public String loadNewsList(DeNewsTitle deNewsTitleVo, @PathVariable("posId") int posId)
这时缓存是不起作用的
之所以不走缓存,是因为每次创建了不同的 DeNewsTitle 对象,缓存的 key 生成策略认为不是同一个参数。解决方法是为 DeNewsTitle 对象添加 equals() 和 hashCode() 实现即可
关于equals和hashCode方法,参见: http://chroya.iteye.com/blog/803972
以上 仅做参考记录
附录:
关于@CacheConfig的使用:
Using @CacheConfig
@CacheConfig annotation is used at class level to share common cache related settings. All the methods of the class annotated with @Cacheable gets a common cache related settings provided by @CacheConfig. The attributes of @CacheConfig are cacheNames, cacheManager, cacheResolver and keyGenerator. We can override the class level cache related setting for a method using attributes of @Cacheable. Find a class annotated with @CacheConfig being used in our demo.
Student.java
package com.concretepage;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames="mycacheone")
public class Student {
@Cacheable
public String getStudentName(int stdId) {
System.out.println("execute getStudentName method...");
if (stdId == 1) {
return "Ramesh";
} else {
return "Mahesh";
}
}
@Cacheable(value = "mycachetwo")
public String getCity(int cityId) {
System.out.println("execute getCity method...");
if (cityId == 1) {
return "Varanasi";
} else {
return "Allahabad";
}
}
}