springboot的几个缓存相关注解

@Cacheable:查询

几个属性:

​ cacheNames/value:指定缓存组件的名字;

​ key:缓存数据使用的key,可以用来指定。默认即使用方法参数的值

​ keyGenerator:key的生成器,可以自己指定key的生成器的组件id

//自定义配置类配置keyGenerator
@Configuration
public class MyCacheConfig {
​
    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString() +"]";
            }
        };
    }
}

​ cacheManager:指定缓存管理器;或者cacheResolver获取指定解析器

​ condition:指定符合条件的情况下才缓存;如condition="#id>0"

​ unless:否定缓存,当unless指定的条件为true,方法的返回值不会被缓存,可以获取到结果进行判断;如unless="#result==null";

​ sync:是否使用异步模式

 @Cacheable(cacheNames = "user",keyGenerator = "myKeyGenerator")
    public User getUser(Integer id) {
        System.out.println("查询" + id + "号用户");
        User user = userMapper.getUserId(id);
        return user;
    }

@CachePut:更新

既调用方法,又更新缓存数据,可达到同步更新缓存;

修改了数据库的某个数据,同时更新缓存

运行时机:

1、先调用运行方法;2、将目标方法的结果缓存起来

value:缓存名 key:缓存的key其中#result表示方法返回的结果(确保更新的key和查询一致即可做到同时更新数据库数据和缓存中的数据)

@CachePut(value="user",key = "#result.id")
    public User updateUser(User user){
        System.out.println("updateUser:"+user);
        userMapper.updateUser(user);
        return user;
    }

@CacheEvict:删除

缓存清除:目的是为了删除一个数据并删掉缓存

key:指定要清除的数据(对应上key可实现目的即同时做到删除数据库和缓存中的数据)

allEntries =true:指定清楚这个缓存中所有的数据

beforeInvocation = false:缓存的清楚是否在方法之前执行,默认代表是在方法之后执行


@CacheEvict(value = "user",key = "#id")
   public void deleteUser(Integer id){
       System.out.println("deleteUser:"+id);
       userMapper.deleteUserById(id);
  }

@Caching:定义复杂的缓存规则

    @Caching(
            cacheable = {
                    @Cacheable()
            },
            put = {
                    @CachePut(),
                    @CachePut()
            },
            evict = {
                    @CacheEvict()
            }
    )
    public 返回值 方法名(参数类型 参数){
        return 返回结果;
    }

@CacheConfig:类公共配置

加在类上,为当前类统一配置,具体进入注解中查看可设置属性,如value="?"统一类下所有的缓存名

原文地址:https://www.cnblogs.com/it-taosir/p/9727951.html