文章目录
- 一、介绍
- 二、常用注解
- 三、快速入门
- 3.1 @EnableCaching
- 3.2 @CachePut
- 3.3 @Cacheable
- 3.4 @CacheEvict
 
一、介绍
Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。
Spring Cache 提供了一层抽象,底层可以切换不同的缓存实现,例如:
- EHCache
- Caffeine
- Redis(常用)
依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId>  		            		       	 <version>2.7.3</version> 
</dependency>
二、常用注解

三、快速入门
3.1 @EnableCaching
启动类添加注解,开启注解缓存使用
 
3.2 @CachePut
@CachePut 说明:
-  作用: 将方法返回值,放入缓存 
-  value: 缓存的名称, 每个缓存名称下面可以有很多key 
-  key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法(pattern) 
	/*** CachePut:将方法返回值放入缓存* value:缓存的名称,每个缓存名称下面可以有多个key* key:缓存的key*/@PostMapping//key的生成:userCache::1@CachePut(value = "userCache", key = "#user.id")public User save(@RequestBody User user){userMapper.insert(user);return user;}
3.3 @Cacheable
-  作用: 在方法执行前,spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中。 - 有就直接调用,没有就新增后调用
 
-  value: 缓存的名称,每个缓存名称下面可以有多个key 
-  key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法 
	/*** Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,	  *调用方法并将方法返回值放到缓存中* value:缓存的名称,每个缓存名称下面可以有多个key* key:缓存的key*/@GetMapping@Cacheable(cacheNames = "userCache",key="#id")public User getById(Long id){User user = userMapper.getById(id);return user;}
再次查询相同id的数据时,直接从redis中直接获取,不再查询数据库。
3.4 @CacheEvict
-  作用: 清理指定缓存 
-  value: 缓存的名称,每个缓存名称下面可以有多个key 
-  key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法 
	@DeleteMapping@CacheEvict(cacheNames = "userCache",key = "#id")//删除某个key对应的缓存数据public void deleteById(Long id){userMapper.deleteById(id);}@DeleteMapping("/delAll")@CacheEvict(cacheNames = "userCache",allEntries = true)//删除userCache下所有的缓存数据public void deleteAll(){userMapper.deleteAll();}