知乎专栏 |
@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 []"
@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"; }
使用 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