Spring Cache是一个框架,实现了基于注解的缓存功能。只需要增加一个注释,就可以实现缓存功能。

Spring Cache提供了一层抽象,底层可以切换不同的Cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。

CacheManager是Spring提供的各种缓存技术的抽象接口。

针对不同的缓存技术,需要实现不同的CacheManager


在Spring Boot项目中,使用缓存技术只需要在项目中导入相关缓存技术的的依赖包,并在启动类上使用 @EnableCaching 开启缓存功能即可。

例如,使用Redis作为缓存技术,只需要导入spring-data-redis的maven坐标即可。


<dependency>

      <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-cache</artifactId>

           <version>2.7.3</version>

      </dependency>

<dependency>

     <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

 

修改配置文件,增加cache,指定Redis作为缓存产品


spring:

 cache:

   redis:

     time-to-live: 180000 #设置缓存过期时间

 redis:

   database: 0

   host: 127.0.0.1

   jedis:

     pool:

       max-idle: 8

       max-wait: 1ms

       max-active: 8

       min-idle: 0

 

Spring cache常用注解说明:



使用 @CachePut 缓存数据

@Autowired

private CacheManager cacheManager;


/*

@CachePut 用于缓存返回值

value表示缓存的名称,相当于一类缓存

key表示该名称下的缓存数据的key

*/

@PostMapping

//用参数的指定属性作为key

@CachePut(value="cacheName",key="#user.id")

public UserInfo insert(UserInfo user){

   //insert业务

   return user;

}


@PutMapping

//用参数作为key

@CachePut(value="cacheName",key="#id")

public String update(String id){

   return "shawn";

}


 

使用 @CacheEvict 删除缓存数据

@Autowired

private CacheManager cacheManager;


/*

@CacheEvict 用于删除缓存数据

value表示缓存的名称,相当于一类缓存

key表示该名称下的缓存数据的key

以下三种获取id值的写法是完全等价的,

*/

@DeleteMapping

@CacheEvict(value="cacheName",key="#id")

//@CacheEvict(value="cacheName",key="#p0") #p0 表示第一个参数

//@CacheEvict(value="cacheName",key="#root.args[0]") #root.args[0] 表示第一个参数

public String del(String id){

   return "delete";

}


 

使用 @Cacheable 缓存数据

@Autowired

private CacheManager cacheManager;


/*

@Cacheable 执行前先查看缓存中是否有数据,有数据则直接从缓存中拿数据,没有则执行方法,并将方法的结果存储到缓存中

value表示缓存的名称,相当于一类缓存

key表示该名称下的缓存数据的key

conditon表示满足条件缓存

unless 表示满足条件不缓存

*/

@GetMapping

//@Cacheable(value="cacheName",key="#id",conditon="#id!=null")

@Cacheable(value="cacheName",key="#id",unless="#return==null")

public UserInfo get(String id){

   UserInfo user=service.getById(id);

   return user;

}


 

最后,返回的类型必须实现序列化接口,否则无法进行缓存。