Spring Cache的使用笔记


Spring Cache常用的注解:@Chacheable, @CacheEvict, @CachePut 使用@Cacheable标记的方法在执行后Spring Cache将缓存其返回结果 使用@CacheEvict标记的方法会在方法执行前或者执行后移除Spring Cache中的某些元素。 常用的三个属性是 value, key, condition  2)@Cacheable可以用在方法上也可以用在类上,方法在对象内部被调用时结果不会被缓存下来。 3)value是必须指定的,可以是多个值,多个值时表示一个数组 如 : @Cacheable({“chache1”,“cache2”}) public User findByName(String name) {   // 返回的USER将会被保存 } 4)使用key属性自定义key,使用EL表达式,可以直接使用“#参数名”“#p参数位置” @Cacheable(value=“users”“key="#name”) public User findByName(String name) {   // 返回的USER将会被保存 } @Cacheable(value="users", key="#p0") public User findByName(String name) {   // 返回的USER将会被保存 } @Cacheable(value="users", key="user.id") public User findByObj(User user) {   // 返回的USER将会被保存 }   5)使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。 6)CachePut是每次都会执行方法,结果放于缓存,因此单纯使用CachePut是没有意义的,可以用于周期任务中更新缓存 7)@CacheEvict是用来标注在需要清除缓存元素的方法或类上的。当标记在一个类上时表示其中所有的方法的执行都会触发缓存的清除操作。 8)补充:@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) {       return null;    }