概要
Spring Cache缓存的基本使用
1.可以通过提供的注解来操作Redis,提高开发效率。
2.一般在Controller层中的 查询、 删除、修改方法上使用。
常用注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能通常加载启动类上 |
@Cacheable | 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将该方法的返回值存到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
实现思路
1.导入Spring Cache和Redis的相关Maven坐标:
<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.在启动类上加入@EnableCaching(开启缓存注解)
@Slf4j
@SpringBootApplication
@EnableCaching//开启缓存注解
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("项目启动成功...");
}
}
3.在用户端或管理端中的:增加、删除、更新操作中加入相应注解
package com.itheima.controller;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserMapper userMapper;
@PostMapping
//如果使用SpringCache缓存数据,key的生成 userCache::用户ID(通过key = "#user.id"取出用户ID)
// @CachePut(cacheNames = "userCache",key = "#user.id") //此参数是从方法参数取到的 尽量用这一个
// @CachePut(cacheNames = "userCache",key = "#result.id") //从方法返回的结果中取到的
@CachePut(cacheNames = "userCache",key = "#p0.id") //代表当前方法的第一个参数 p1代表第二个参数 三个随便一个都可以
public User save(@RequestBody User user){
userMapper.insert(user);
return user;
}
@GetMapping
@Cacheable(cacheNames = "userCache",key = "#id") //生成的key userCache::id(参数中的id) 注意此参数不能调用result.id
public User getById(Long id){
User user = userMapper.getById(id);
return user;
}
@DeleteMapping
@CacheEvict(cacheNames = "userCache",key = "#id")
public void deleteById(Long id){
userMapper.deleteById(id);
}
@CacheEvict(cacheNames = "userCache",allEntries = true) //allEntries = true 表示要删除userCache下的所有键值对
@DeleteMapping("/delAll")
public void deleteAll(){
userMapper.deleteAll();
}
}
配置项
application.yml配置文件中要添加的数据:
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 1 //几号数据库
注意事项
程序启动前要
开启Redis!!!
开启Redis!!!
开启Redis!!!