目的:缓存可以通过将经常访问的数据存储在内存中,减少底层数据源如数据库的压力,从而有效提高系统的性能和稳定性。
一、启用缓存@EnableCaching
我们需要在启动类上添加注解@EnableCaching来开启缓存功能。
示例代码如下:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
// 开启缓存功能
@EnableCaching
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
二、缓存的使用之@Cacheable
开启缓存后,我们可以使用@Cacheable、@CachePut、@CacheEvict注解来使用缓存。
@Cacheable:该注解可以将方法运行的结果直接进行缓存,在缓存有效期内再次调用该方法时不会调用方法本身,而是直接从缓存中获取结果并返回给调用方。
属性名 | 描述 |
value/cacheNames | 指定缓存的名称 |
key | 缓存数据时key的值,默认使用方法的参数值 |
keyGenerator | 缓存的key生成策略(和key只能二选一) |
cacheManager | 指定的缓存管理器(Redis等) |
cacheResolver | 作用和cacheManager属性一样,也是只能二选一 |
condition | 指定的缓存条件 (满足才会去缓存) |
unless | 如果满足unless指定条件,方法不进行缓存 |
sync | 是否使用异步方式进行缓存 默认为false |
@Cacheable测试:
1.添加依赖和项目配置文件
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
# jpa使用update模式配置数据库
spring.jpa.hibernate.ddl-auto=update
# 显示数据执行语句
spring.jpa.show-sql=true
#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true
我们使用jpa的方式创建数据处理层。
2.创建数据实体
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author qx
* @date 2023/06/19
* @desc 数据实体
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_student")
public class Student implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 姓名
*/
@Column
private String name;
/**
* 年龄
*/
@Column
private Integer age;
}
3.创建数据访问层
import com.example.myspringboot.bean.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student,Long> {
}
4.创建服务层
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author qx
* @date 2023/06/19
* @desc 服务层
*/
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
@Cacheable(value = "student")
public List<Student> getAllStudent(){
return studentRepository.findAll();
}
}
5.创建测试控制器
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @author qx
* @date 2023/06/19
* @desc
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/all")
public List<Student> getAllStudent(){
return studentService.getAllStudent();
}
}
6.启动项目,访问请求接口
2023-06-19 17:49:45.768 INFO 10012 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 17:49:45.768 INFO 10012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-19 17:49:45.769 INFO 10012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_, student0_.age as age2_0_, student0_.name as name3_0_ from t_student student0_
看到控制台打印了sql执行语句。我们再次访问这一个接口,并把浏览器的消息清除。
继续查询到了数据,但是控制台的sql语句并没有执行,从而实现了从缓存中获取数据。
三、缓存的使用之@CachePut
@CachePut:标注该注解的方法,在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果写入到指定的缓存中。一般用于更新缓存。
服务层:
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* @author qx
* @date 2023/06/19
* @desc 服务层
*/
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
@Cacheable(value = "student")
public Student getStudent() {
return studentRepository.findById(1L).get();
}
/**
* 修改数据并写入到指定的缓存
*/
@CachePut(value = "student")
public Student updateStudent() {
Optional<Student> studentOptional = studentRepository.findById(1L);
Student student = studentOptional.get();
student.setName("test2");
// 修改数据
studentRepository.save(student);
return student;
}
}
控制层:
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author qx
* @date 2023/06/19
* @desc
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/one")
public Student getStudent() {
return studentService.getStudent();
}
@GetMapping("/update")
public Student updateStudent() {
return studentService.updateStudent();
}
}
测试:
2023-06-19 18:08:56.936 INFO 8064 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:08:56.936 INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:08:56.937 INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?
Hibernate: update t_student set age=?, name=? where id=?
我们重新查询数据,发现没有执行sql语句,但是查询使用了更新后的缓存数据。
2023-06-19 18:08:56.936 INFO 8064 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:08:56.936 INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:08:56.937 INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?
Hibernate: update t_student set age=?, name=? where id=?
四、缓存的使用之@CacheEvict
标注了@CacheEvict注解的方法被调用的时候,会从缓存中移除已存储的数据,这个注解一般用于删除缓存数据。
属性名 | 描述 |
value/cacheNames | 缓存的名称 |
key | 缓存的键 |
allEntries | 是否根据缓存名称清空所有的缓存数据,默认为false,当为true时,将忽略注解上指定的key属性 |
beforeInvocation | 是否在方法执行之前就清空缓存 默认为false |
服务层:
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
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.stereotype.Service;
import java.util.Optional;
/**
* @author qx
* @date 2023/06/19
* @desc 服务层
*/
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
@Cacheable(value = "student")
public Student getStudent() {
return studentRepository.findById(1L).get();
}
/**
* 修改数据并写入到指定的缓存
*/
@CachePut(value = "student")
public Student updateStudent() {
Optional<Student> studentOptional = studentRepository.findById(1L);
Student student = studentOptional.get();
student.setName("test2");
// 修改数据
studentRepository.save(student);
return student;
}
/**
* 清除缓存
*/
@CacheEvict(value = "student")
public void deleteCache() {
System.out.println("清除缓存");
}
}
控制层:
import com.example.myspringboot.bean.Student;
import com.example.myspringboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author qx
* @date 2023/06/19
* @desc
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/one")
public Student getStudent() {
return studentService.getStudent();
}
@GetMapping("/update")
public Student updateStudent() {
return studentService.updateStudent();
}
@GetMapping("/clearCache")
public void clearCache(){
studentService.deleteCache();
}
}
先调用清除缓存的接口,再访问查询接口。
控制台显示:
2023-06-19 18:22:12.955 INFO 6440 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:22:12.956 INFO 6440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:22:12.957 INFO 6440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
清除缓存
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?
我们从控制台可以看到清除缓存后,再次请求查询的接口会重新执行查询的sql语句。
标签:缓存,SpringBoot,cache,springframework,student,import,org,public From: https://blog.51cto.com/u_13312531/6516922