Spring Cache是一个框架,实现了基于注解的缓存功能。通过不同的CacheManager接口来管理不同的缓存技术,例如使用Redis作为缓存技术,其接口为RedisCacheManager。(如果不用任何缓存技术,spring为我们提供了一个map,它也可以作为缓存,只不过服务停止,它的缓存数据就没有了,只能通过数据库找到)
Spring Cache常用注解
@EnableCaching:开启缓存注解功能,一般加到项目的启动类中。
@Cacheable:在方法执行前,spring首先查看缓存中是否有数据,如果有,则直接返回缓存数据,如果没有,则调用该方法,将返回结果加在缓存中。
@CachePut:将方法的返回值加入缓存中。
@CacheEvict:将若干条数据从缓存中删除。(allEntries=ture:删除value下的所有)
准备条件:
导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching注解即可
运用:
不使用缓存技术,用spring为我们提供的map。此时不需要导入额外的依赖包。
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private CacheManager cacheManager;
@Autowired
private UserService userService;
/**
* 将方法返回值放入缓存
* value:缓存的名称,每个缓存名称下面有多个key
*key:缓存的key
* @param user
* @return
*/
@CachePut(value = "userCache",key="#user.id")
@PostMapping
public User save(User user){
System.out.println(user);
userService.save(user);
return user;
}
/**
* 清理指定缓存
* value:缓存的名称,每个缓存名称下面有多个key
*key:缓存的key
*/
@CacheEvict(value = "userCache",key = "#id")
// @CacheEvict(value = "userCache",key = "#root.args[0]")
// @CacheEvict(value = "userCache",key = "#p0")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
// @CacheEvict(value = "userCache",key = "#user.id")
// @CacheEvict(value = "userCache",key = "#root.args[0].id")
// @CacheEvict(value = "userCache",key = "#p0。id")
@CacheEvict(value = "userCache",key = "#result.id")
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
/**
* 在方法执行前,spring首先查看缓存中是否有数据,如果有,则直接返回缓存数据,如果没有,则调用该方法,将返回结果加在缓存中。
* condition:条件缓存
* @param id
* @return
*/
@Cacheable(value = "userCache",key = "#id",condition = "#result!=null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
@Cacheable(value = "userCache",key = "#user.id+'_'+#user.name")
@GetMapping("/list")
public List<User> list(User user){
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(user.getId() != null,User::getId,user.getId());
queryWrapper.eq(user.getName() != null,User::getName,user.getName());
List<User> list = userService.list(queryWrapper);
return list;
}
}
使用redis缓存技术
1、导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置文件
在spring目录下配置
redis: host: 127.0.0.1 port: 6379 database: 0 #password: root@123456 cache: redis: time-to-live: 1800000 #设置缓存过期时间
controller类的代码与上面未使用redis类似
不同的地方在如下:
@Cacheable(value = "userCache",key = "#id",unless = "#result==null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
将condition换成unless,这里用result的话就不能用condition(有没有大佬具体解释一下)
注意测试时打开redis服务!
跟着黑马学技术!!