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

 更新时间:2022年10月28日 09:45:14   作者:showswoller  
我们知道内存读取速度远大于硬盘读取速度,当需要重复获取相同数据时,一次一次的请求数据库或者远程服务,导致在数据库查询或者远程方法调用上小号大量的时间,最终导致程序性能降低,这就是数据缓存要解决的问题,学过计算机组成原理或者操作系统的同学们应该比较熟悉

一、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依赖

<?xml version="1.0" encoding="UTF-8"?>
-<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">
<modelVersion>4.0.0</modelVersion>
-<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>com.ch</groupId>
<artifactId>ch6_10</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ch6_10</name>
<description>Demo project for Spring Boot</description>
-<properties>
<java.version>11</java.version>
</properties>
-<dependencies>
-<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
-<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
-<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加MySQL依赖 -->
-<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
<!-- MySQL8.x时,请使用8.x的连接器 -->
</dependency>
-<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
-<build>
-<plugins>
-<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

4:创建持久化实体类

代码如下

package com.ch.ch6_10.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "student_table")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer"})
public class Student implements Serializable{
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;//主键
	private String sno;
	private String sname;
	private String ssex;
	public Student() {
		super();
	}
	public Student(int id, String sno, String sname, String ssex) {
		super();
		this.id = id;
		this.sno = sno;
		this.sname = sname;
		this.ssex = ssex;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getSsex() {
		return ssex;
	}
	public void setSsex(String ssex) {
		this.ssex = ssex;
	}  
}

5:创建数据访问接口

package com.ch.ch6_10.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ch.ch6_10.entity.Student;
public interface StudentRepository extends JpaRepository<Student, Integer>{
}

6:创建业务层 包括一个接口和一个实现类

接口代码如下

package com.ch.ch6_10.service;
import com.ch.ch6_10.entity.Student;
public interface StudentService {
	public Student saveStudent(Student student);
	public void deleteCache(Student student);
	public Student selectOneStudent(Integer id);
}

实现类代码如下

package com.ch.ch6_10.service;
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 com.ch.ch6_10.entity.Student;
import com.ch.ch6_10.repository.StudentRepository;
@Service
public class StudentServiceImpl implements StudentService{
	@Autowired
	private StudentRepository studentRepository;
	@Override
	@CachePut(value = "student", key="#student.id")
	public Student saveStudent(Student student) {
		Student s = studentRepository.save(student);
		System.out.println("为key=" + student.getId() + "数据做了缓存");
		return s;
	}
	@Override
	@CacheEvict(value = "student", key="#student.id")
	public void deleteCache(Student student) {
		System.out.println("删除了key=" + student.getId() + "的数据缓存");
	}
	@Override
	@Cacheable(value = "student")
	public Student selectOneStudent(Integer id) {
		Student s = studentRepository.getOne(id);
		System.out.println("为key=" + id + "数据做了缓存");
		return s;
	}
}

7:创建控制器层

package com.ch.ch6_10.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ch.ch6_10.entity.Student;
import com.ch.ch6_10.service.StudentService;
@RestController
public class TestCacheController {
	@Autowired
	private StudentService studentService;
	@RequestMapping("/savePut")
	public Student save(Student student) {
		return studentService.saveStudent(student);
	}
	@RequestMapping("/selectAble")
	public Student select(Integer id) {
		return studentService.selectOneStudent(id);
	}
	@RequestMapping("/deleteEvict")
	public String deleteCache(Student student) {
		studentService.deleteCache(student);
		return "ok";
	}
}

8:在主类中开启缓存支持

package com.ch.ch6_10;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class Ch610Application {
	public static void main(String[] args) {
		SpringApplication.run(Ch610Application.class, args);
	}
}

到此这篇关于SpringBoot与Spring中数据缓存Cache超详细讲解的文章就介绍到这了,更多相关SpringBoot数据缓存Cache内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • mybatis-plus之自动映射字段(typeHandler)的注意点及说明

    mybatis-plus之自动映射字段(typeHandler)的注意点及说明

    这篇文章主要介绍了mybatis-plus之自动映射字段(typeHandler)的注意点及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • java短路逻辑运算符实例用法详解

    java短路逻辑运算符实例用法详解

    在本篇文章里小编给大家分享的是一篇关于java短路逻辑运算符实例用法内容,有需要的朋友们可以学习参考下。
    2021-04-04
  • java异常和错误类总结(必看篇)

    java异常和错误类总结(必看篇)

    下面小编就为大家带来一篇java异常和错误类总结(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-09-09
  • Mybatis执行Update返回行数为负数的问题

    Mybatis执行Update返回行数为负数的问题

    这篇文章主要介绍了Mybatis执行Update返回行数为负数的问题,具有很好的参考价值,希望大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • springboot集成微软teams的实例代码

    springboot集成微软teams的实例代码

    Microsoft Teams 是一款基于聊天的智能团队协作工具,可以同步进行文档共享,并为成员提供包括语音、视频会议在内的即时通讯工具,今天给大家介绍springboot集成微软teams的示例代码,感兴趣的朋友一起看看吧
    2022-01-01
  • springboot升级到jdk21最新教程(2023年)

    springboot升级到jdk21最新教程(2023年)

    你还在使用jdk8?快来看看最新出炉的SpringBoot+jdk21如何使用,下面这篇文章主要给大家介绍了关于springboot升级到jdk21的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-10-10
  • Java多线程中的ThreadPoolExecutor使用解析

    Java多线程中的ThreadPoolExecutor使用解析

    这篇文章主要介绍了Java多线程中的ThreadPoolExecutor使用解析,作为线程池的缓冲,当新增线程超过maximumPoolSize时,会将新增线程暂时存放到该队列中,需要的朋友可以参考下
    2023-12-12
  • arthas jprofiler做复杂链路的调用分析

    arthas jprofiler做复杂链路的调用分析

    这篇文章主要为大家介绍了arthas jprofiler做复杂链路的调用分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • SpringBoot环境Druid数据源使用及特点

    SpringBoot环境Druid数据源使用及特点

    Druid 是目前比较流行的高性能的,分布式列存储的OLAP框架(具体来说是MOLAP)。本文给大家分享SpringBoot环境Druid数据源使用及特点介绍,感兴趣的朋友跟随小编一起看看吧
    2021-07-07
  • SpringBoot项目实用功能之实现自定义参数解析器

    SpringBoot项目实用功能之实现自定义参数解析器

    这篇文章主要介绍了SpringBoot项目实用功能之实现自定义参数解析器,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08

最新评论