启用缓存支持

@Configuration
@ComponentScan("wang.ismy.spring")
@EnableCaching
public class Config {

    @Bean
    public CacheManager cacheManager(){
        return new ConcurrentMapCacheManager();
    }


}
  • Spring 提供的几个缓存管理器 批注 2019-06-21 150246

让方法支持缓存

@Cacheable(value = "find",key = "#id")
    public String find(Integer id){
        System.out.println("real find");
        return "hello world"+id;
    }
  • 将值放到缓存当中

    /**
       * 该方法肯定会被执行,但是返回结果会放到缓存当中
       */
      @CachePut(value = "find",key = "#id")
      public String put(Integer id){
    
          return "new"+id;
      }
    
  • 条件化缓存

    • unless : 阻止将对象放入缓存,但是还会进行缓存查找
    • condition : 不会进行缓存查找,也不会将结果放入缓存

在id等于10时不会进行缓存

@Cacheable(value = "find",key = "#id",condition = "#id != 10")
    public String find(Integer id){
        System.out.println("real find");
        return "hello world"+id;
    }
  • 移除缓存

    @CacheEvict(value = "find",key = "#id")
      public void remove(Integer id){
    
      }
    

使用xml添加缓存

results matching " "

No results matching " "

results matching " "

No results matching " "