[JAVA] SpringBoot与Spring中数据缓存Cache超详细讲解

1871 0
王子 2022-11-8 18:00:40 | 显示全部楼层 |阅读模式
目录

    一、Spring缓存支持
      1、@Cacheable2、@CacheEvict3、@CachePut4、Caching5、CacheConfig
    二、Spring Boot缓存支持


一、Spring缓存支持

Spring框架定义了org.springframework.cache CacheManager和org.springframework.cache.Cache接口来统一不同的缓存技术
CacheManager常用方法如下



1、@Cacheable

该注解可以标记在一个方法上,也可以标记在一个类上,当标记在一个方法上时表示该方法是支持缓存的,当标记在一个类上时则表示该类所有的方法都是支持缓存的。对于一个支持缓存的方法,在方法执行前,Spring先检查缓存中是否存在方法返回的数据,如果存在则直接返回缓存数据,如果不存在,则调用方法并将方法返回值存入缓存

2、@CacheEvict

该注解用来标注在需要清楚缓存元素的方法或类上,当标记在一个类上时,表示其中所有方法的执行都会触发缓存的清除操作

3、@CachePut

该注解也可以声明一个方法支持缓存功能

4、Caching

该注解可以在一个方法或类上同时指定多个Spring Cache相关的注解

5、CacheConfig

该注解作用在类上可以设置当前缓存的一些公共设置

二、Spring Boot缓存支持

1:创建基于spring-voot-starter-cache 和spring-boot-starter-data-jpa依赖的Spring BootWeb应用
2:配置application.properties文件 代码如下
server.servlet.context-path=/ch6_10
###
##数据源信息配置
###
#数据库地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=utf8
#数据库用户名
spring.datasource.username=root
#数据库密码
spring.datasource.password=root
#数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
####
#JPA持久化配置
####
#指定数据库类型
spring.jpa.database=MYSQL
#指定是否在日志中显示SQL语句
spring.jpa.show-sql=true
#指定自动创建、更新数据库表等配置,update表示如果数据库中存在持久化类对应的表就不创建,不存在就创建对应的表
spring.jpa.hibernate.ddl-auto=update
#让控制器输出的JSON字符串格式更美观
spring.jackson.serialization.indent-output=true
3:修改pom.xml文件 添加mysql依赖
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0">
  3. <modelVersion>4.0.0</modelVersion>
  4. -<parent>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-parent</artifactId>
  7. <version>2.1.8.RELEASE</version>
  8. <relativePath/>
  9. <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.ch</groupId>
  12. <artifactId>ch6_10</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>ch6_10</name>
  15. <description>Demo project for Spring Boot</description>
  16. -<properties>
  17. <java.version>11</java.version>
  18. </properties>
  19. -<dependencies>
  20. -<dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-cache</artifactId>
  23. </dependency>
  24. -<dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-data-jpa</artifactId>
  27. </dependency>
  28. -<dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32. <!-- 添加MySQL依赖 -->
  33. -<dependency>
  34. <groupId>mysql</groupId>
  35. <artifactId>mysql-connector-java</artifactId>
  36. <version>5.1.45</version>
  37. <!-- MySQL8.x时,请使用8.x的连接器 -->
  38. </dependency>
  39. -<dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. </dependencies>
  45. -<build>
  46. -<plugins>
  47. -<plugin>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-maven-plugin</artifactId>
  50. </plugin>
  51. </plugins>
  52. </build>
  53. </project>
复制代码
4:创建持久化实体类
代码如下
  1. package com.ch.ch6_10.entity;
  2. import java.io.Serializable;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8. import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
  9. @Entity
  10. @Table(name = "student_table")
  11. @JsonIgnoreProperties(value = {"hibernateLazyInitializer"})
  12. public class Student implements Serializable{
  13.         private static final long serialVersionUID = 1L;
  14.         @Id
  15.         @GeneratedValue(strategy = GenerationType.IDENTITY)
  16.         private int id;//主键
  17.         private String sno;
  18.         private String sname;
  19.         private String ssex;
  20.         public Student() {
  21.                 super();
  22.         }
  23.         public Student(int id, String sno, String sname, String ssex) {
  24.                 super();
  25.                 this.id = id;
  26.                 this.sno = sno;
  27.                 this.sname = sname;
  28.                 this.ssex = ssex;
  29.         }
  30.         public int getId() {
  31.                 return id;
  32.         }
  33.         public void setId(int id) {
  34.                 this.id = id;
  35.         }
  36.         public String getSno() {
  37.                 return sno;
  38.         }
  39.         public void setSno(String sno) {
  40.                 this.sno = sno;
  41.         }
  42.         public String getSname() {
  43.                 return sname;
  44.         }
  45.         public void setSname(String sname) {
  46.                 this.sname = sname;
  47.         }
  48.         public String getSsex() {
  49.                 return ssex;
  50.         }
  51.         public void setSsex(String ssex) {
  52.                 this.ssex = ssex;
  53.         }  
  54. }
复制代码
5:创建数据访问接口
  1. package com.ch.ch6_10.repository;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import com.ch.ch6_10.entity.Student;
  4. public interface StudentRepository extends JpaRepository<Student, Integer>{
  5. }
复制代码
6:创建业务层 包括一个接口和一个实现类
接口代码如下
  1. package com.ch.ch6_10.service;
  2. import com.ch.ch6_10.entity.Student;
  3. public interface StudentService {
  4.         public Student saveStudent(Student student);
  5.         public void deleteCache(Student student);
  6.         public Student selectOneStudent(Integer id);
  7. }
复制代码
实现类代码如下
  1. package com.ch.ch6_10.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.cache.annotation.CacheEvict;
  4. import org.springframework.cache.annotation.CachePut;
  5. import org.springframework.cache.annotation.Cacheable;
  6. import org.springframework.stereotype.Service;
  7. import com.ch.ch6_10.entity.Student;
  8. import com.ch.ch6_10.repository.StudentRepository;
  9. @Service
  10. public class StudentServiceImpl implements StudentService{
  11.         @Autowired
  12.         private StudentRepository studentRepository;
  13.         @Override
  14.         @CachePut(value = "student", key="#student.id")
  15.         public Student saveStudent(Student student) {
  16.                 Student s = studentRepository.save(student);
  17.                 System.out.println("为key=" + student.getId() + "数据做了缓存");
  18.                 return s;
  19.         }
  20.         @Override
  21.         @CacheEvict(value = "student", key="#student.id")
  22.         public void deleteCache(Student student) {
  23.                 System.out.println("删除了key=" + student.getId() + "的数据缓存");
  24.         }
  25.         @Override
  26.         @Cacheable(value = "student")
  27.         public Student selectOneStudent(Integer id) {
  28.                 Student s = studentRepository.getOne(id);
  29.                 System.out.println("为key=" + id + "数据做了缓存");
  30.                 return s;
  31.         }
  32. }
复制代码
7:创建控制器层
  1. package com.ch.ch6_10.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import com.ch.ch6_10.entity.Student;
  6. import com.ch.ch6_10.service.StudentService;
  7. @RestController
  8. public class TestCacheController {
  9.         @Autowired
  10.         private StudentService studentService;
  11.         @RequestMapping("/savePut")
  12.         public Student save(Student student) {
  13.                 return studentService.saveStudent(student);
  14.         }
  15.         @RequestMapping("/selectAble")
  16.         public Student select(Integer id) {
  17.                 return studentService.selectOneStudent(id);
  18.         }
  19.         @RequestMapping("/deleteEvict")
  20.         public String deleteCache(Student student) {
  21.                 studentService.deleteCache(student);
  22.                 return "ok";
  23.         }
  24. }
复制代码
8:在主类中开启缓存支持
  1. package com.ch.ch6_10;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. @EnableCaching
  6. @SpringBootApplication
  7. public class Ch610Application {
  8.         public static void main(String[] args) {
  9.                 SpringApplication.run(Ch610Application.class, args);
  10.         }
  11. }
复制代码
到此这篇关于SpringBoot与Spring中数据缓存Cache超详细讲解的文章就介绍到这了,更多相关SpringBoot数据缓存Cache内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行