Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

34.3. @Cacheable 的用法

        
@Cacheable(value="users", key="#id")
public User find(Integer id) {

	return null;

}			
        
		

引用对象

        
@Cacheable(value="users", key="#user.id")
public User find(User user) {

return null;

}			
        
		

条件判断

        
@Cacheable(value="messagecache", key="#id", condition="id < 10")
public String getMessage(int id){

return "hello"+id;

}

@Cacheable(value="test",condition="#userName.length()>2")
@Cacheable(value={"users"}, key="#user.id", condition="#user.id%2==0")
        
		

#p0 参数索引,p0表示第一个参数

        
@Cacheable(value="users", key="#p0")
public User find(Integer id) {

return null;

}

@Cacheable(value="users", key="#p0.id")
public User find(User user) {

return null;

}
        
		

@Cacheable 如果没有任何参数将会自动生成 key ,前提是必须设置 @CacheConfig(cacheNames = "test")

        
@GetMapping("/cache/auto")
@Cacheable()
public Attribute auto() {
    Attribute attribute = new Attribute();
    attribute.setName("sdfsdf");
    return attribute;
}			
        
		
        
127.0.0.1:6379> keys *
1) "test::SimpleKey []"			
        
		

34.3.1. SpEL表达式

        
@GetMapping("/cache/expire")
@Cacheable("test1#${select.cache.timeout:1000}")
public String expire() {
    return "Test";
}

@GetMapping("/cache/expire")
@Cacheable("test1#${select.cache.timeout:1000}#${select.cache.refresh:600}")
public String expire() {
    return "Test";
}
        
			

34.3.2. 排除 null 结果

使用 unless 排除 null 结果

			
    @Cacheable(value = "translate", key = "#chinese", unless="#result == null")
    public String translate(String chinese) {
    }			
			
			

通过配置文件设置spring.cache.redis.cache-null-values

			
spring.cache.redis.cache-null-values=false			
			
			

34.3.3. 排除 empty

List 不会返回 null,怎么不缓存空的 list 呢?使用 unless="#result.empty" 可以实现

			
@Cacheable(unless="#result.empty")
public List<Object> getList() {
  // method implementation
}