1 Spring缓存抽象

Spring3.1版本开始提供了对缓存的支持,缓存抽象通过**org.springframework.cache.Cache**和**org.springframework.cache.CacheManager**接口来对不同的缓存实现技术提供统一的接口。从Spring 4.1开始支持使用 JCache(JSR-107)注解简化我们开发。

一个CacheManager管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一的名字;
image.png
Spring缓存应用于Java方法上,可以减少方法的调用次数。每次调用添加了缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。

Spring提供了一些缓存抽象的实现

  • 基于JDKjava.util.concurrent.ConcurrentMap的缓存
  • 基于 Ehcache 的缓存
  • JSR-107 缓存
  • …

Spring缓存抽象 常用概念和注解

CacheManager(接口) 缓存管理器,管理各种缓存(Cache)组件
Cache(接口) 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、
ConcurrentMapCache等
@Cacheable 申明在方法上,使方法具有缓存功能,会缓存该方法的返回值。以后再要相同的数据,直接从缓存中获取,不用调用方法
@CacheEvict 申明在方法上,删除缓存中的数据
@CachePut 申明在方法上,每次调用方法时,都会触发缓存机制,将最新的结果保存到缓存中
@Caching 申明在方法上,组合多个缓存注解
@CacheConfig 申明在类上,对类中的缓存进行统一的配置,优先级低于方法上的配置

1.1 快速体验

  1. 导入缓存依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-cache</artifactId>
    4. </dependency>
  2. 开启注解缓存功能 @EnableCaching

    @EnableCaching
    @SpringBootApplication
    public class Springboot02Application {
     public static void main(String[] args) {
         SpringApplication.run(Springboot02Application.class, args);
     }
    }
    
  3. 添加缓存注解 @Cacheable(“dept”),指定缓存组件的名字为”dept”

    @Service
    public class DepartmentService {
    
     @Autowired
     private DepartmentMapper departmentMapper;
    
     @Cacheable("dept")
     public Department getDept(Integer id){
         System.out.println("====getDept()方法执行了====");
         Department department = departmentMapper.findById(id);
         return department;
     }
    }
    

    第一次调用getDept(1)时,会执行该方法,第二次再调用时就直接从缓存中取数据,不会调用方法。

1.2 缓存注解

1.2.1 @Cacheable

**

1.2.2

1.2.3

1.2.4