我们使用的最基础的Spring缓存注解如下:
@Cacheable 生成缓存 一般用在查询Service接口上
@Cacheable(value={"users"}, key=" #root.methodName + #user.id", condition="#user.id%2==0")
public User find(User user) {
System.out.println("find user by user " + user);
return user;
}
key绑定方法接受的参数,根据参数的不同会生存相应不同的缓存。
condition为缓存触发条件,满足此条件才会触发缓存,不写默认缓存所有。
@CacheEvict 删除缓存 一般用在增删改的Service接口上,保证数据库数据和缓存的同步
@CacheEvict(value="users", key = " '自定义字符串'+ #id" ,allEntries=false)
public void delete(Integer id) {
System.out.println("delete user by id: " + id);
}
allEntries=true 这个属性直接删除由values外层键下面的所有缓存
@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
@Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),
@CacheEvict(value = "cache3", allEntries = true) })
public User find(Integer id) {
returnnull;
}