马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
配景
除了 RedisTemplate 外, 自Spring3.1开始,Spring自带了对缓存的支持。我们可以直接利用Spring缓存技能将某些数据放入本机的缓存中;Spring缓存技能也可以搭配其他缓存中央件(如Redis等)进利用用,将某些数据写入到缓存中央件(缓存中央件大概在其他呆板上)中。
常用缓存
- @EnableCaching: 开启缓存注解功能,通常加在启动类上
- @Cacheable: 在方法实行前先查询缓存中是否有数据,假如有数据,则直接返回缓存数据,假如没有缓存数据,调用方法并将方法返回值放到缓存中。
- @CachePut: 将方法的返回值放到缓存中。
- @CacheEvit: 将一条大概多条数据从缓存中删除。
利用
1. 添加依靠并设置redis信息
在 pom.xml 中添加依靠- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
复制代码 在 application.yml 文件中添加依靠- spring:
- redis:
- host: 192.168.**.***
- port: ****
- password: ****
- database: 1
复制代码 2. 在启动类上添加 @EnableCaching 注解
3. 利用缓存注解
- package com.itheima.controller;
- @RestController
- @RequestMapping("/user")
- @Slf4j
- public class UserController {
- @Autowired
- private UserMapper userMapper;
- @PostMapping
- // 使用 @CachePut 添加缓存数据, key 的生成: userCache::user.id,例如 userCache::12
- @CachePut(cacheNames = "userCache", key = "#user.id")
- public User save(@RequestBody User user){
- userMapper.insert(user);
- return user;
- }
- @DeleteMapping
- // 删除指定缓存
- @CacheEvict(cacheNames = "userCache", key = "#id")
- public void deleteById(Long id){
- userMapper.deleteById(id);
- }
- @DeleteMapping("/delAll")
- // 删除所有缓存
- @CacheEvict(cacheNames = "userCache", allEntries = true)
- public void deleteAll(){
- userMapper.deleteAll();
- }
- @GetMapping
- // key 的生成: userCache::12
- @Cacheable(cacheNames = "userCache", key = "#id")
- public User getById(Long id){
- User user = userMapper.getById(id);
- return user;
- }
- }
复制代码 4. 结果
这里以 @CachePut 注解为例演示结果。
向表中添加数据后可以看到乐成将新用户信息添加到了缓存中。
缓存中信息
|