Spring Boot与Spring中的数据缓存Cache支持与实战(附源码)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: Spring Boot与Spring中的数据缓存Cache支持与实战(附源码)

创作不易  觉得有帮助请点赞关注收藏

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

一、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);
  }
}
相关文章
|
1月前
|
安全 Java Apache
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 身份和权限认证
本文介绍了 Apache Shiro 的身份认证与权限认证机制。在身份认证部分,分析了 Shiro 的认证流程,包括应用程序调用 `Subject.login(token)` 方法、SecurityManager 接管认证以及通过 Realm 进行具体的安全验证。权限认证部分阐述了权限(permission)、角色(role)和用户(user)三者的关系,其中用户可拥有多个角色,角色则对应不同的权限组合,例如普通用户仅能查看或添加信息,而管理员可执行所有操作。
80 0
|
1月前
|
安全 Java 数据安全/隐私保护
微服务——SpringBoot使用归纳——Spring Boot中集成 Shiro——Shiro 三大核心组件
本课程介绍如何在Spring Boot中集成Shiro框架,主要讲解Shiro的认证与授权功能。Shiro是一个简单易用的Java安全框架,用于认证、授权、加密和会话管理等。其核心组件包括Subject(认证主体)、SecurityManager(安全管理员)和Realm(域)。Subject负责身份认证,包含Principals(身份)和Credentials(凭证);SecurityManager是架构核心,协调内部组件运作;Realm则是连接Shiro与应用数据的桥梁,用于访问用户账户及权限信息。通过学习,您将掌握Shiro的基本原理及其在项目中的应用。
85 0
|
14天前
|
前端开发 Java 物联网
智慧班牌源码,采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署
智慧班牌系统是一款基于信息化与物联网技术的校园管理工具,集成电子屏显示、人脸识别及数据交互功能,实现班级信息展示、智能考勤与家校互通。系统采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署与私有化定制。核心功能涵盖信息发布、考勤管理、教务处理及数据分析,助力校园文化建设与教学优化。其综合性和可扩展性有效打破数据孤岛,提升交互体验并降低管理成本,适用于日常教学、考试管理和应急场景,为智慧校园建设提供全面解决方案。
181 70
|
27天前
|
前端开发 Java Maven
Spring 和 Spring Boot 之间的比较
本文对比了标准Spring框架与Spring Boot的区别,重点分析两者在模块使用(如MVC、Security)上的差异。Spring提供全面的Java开发基础设施支持,包含依赖注入和多种开箱即用的模块;而Spring Boot作为Spring的扩展,通过自动配置、嵌入式服务器等功能简化开发流程。文章还探讨了两者的Maven依赖、Mvc配置、模板引擎配置、启动方式及打包部署等方面的异同,展示了Spring Boot如何通过减少样板代码和配置提升开发效率。总结指出,Spring Boot是Spring的增强版,使应用开发、测试与部署更加便捷高效。
210 10
|
1月前
|
消息中间件 存储 Java
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
本教程介绍ActiveMQ的安装与基本使用。首先从官网下载apache-activemq-5.15.3版本,解压后即可完成安装,非常便捷。启动时进入解压目录下的bin文件夹,根据系统选择win32或win64,运行activemq.bat启动服务。通过浏览器访问`http://127.0.0.1:8161/admin/`可进入管理界面,默认用户名密码为admin/admin。ActiveMQ支持两种消息模式:点对点(Queue)和发布/订阅(Topic)。前者确保每条消息仅被一个消费者消费,后者允许多个消费者同时接收相同消息。
67 0
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ安装
|
1月前
|
消息中间件 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——发布/订阅消息的生产和消费
本文详细讲解了Spring Boot中ActiveMQ的发布/订阅消息机制,包括消息生产和消费的具体实现方式。生产端通过`sendMessage`方法发送订阅消息,消费端则需配置`application.yml`或自定义工厂以支持topic消息监听。为解决点对点与发布/订阅消息兼容问题,可通过设置`containerFactory`实现两者共存。最后,文章还提供了测试方法及总结,帮助读者掌握ActiveMQ在异步消息处理中的应用。
88 0
|
1月前
|
消息中间件 网络协议 Java
微服务——SpringBoot使用归纳——Spring Boot中集成ActiveMQ——ActiveMQ集成
本文介绍了在 Spring Boot 中集成 ActiveMQ 的详细步骤。首先通过引入 `spring-boot-starter-activemq` 依赖并配置 `application.yml` 文件实现基本设置。接着,创建 Queue 和 Topic 消息类型,分别使用 `ActiveMQQueue` 和 `ActiveMQTopic` 类完成配置。随后,利用 `JmsMessagingTemplate` 实现消息发送功能,并通过 Controller 和监听器实现点对点消息的生产和消费。最后,通过浏览器访问测试接口验证消息传递的成功性。
46 0
|
存储 缓存 NoSQL
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
快速学习 Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
|
Java Go Nacos
3.10 Spring Cloud Gateway 实战接入 Nacos 服务 | 学习笔记
快速学习 3.10 Spring Cloud Gateway 实战接入 Nacos 服务 。
3.10 Spring Cloud Gateway 实战接入 Nacos 服务 | 学习笔记
|
Cloud Native Java 测试技术
3.9 Spring Cloud Gateway 微服务新网关实战| 学习笔记
快速学习 3.9 Spring Cloud Gateway 微服务新网关实战。
3.9 Spring Cloud Gateway 微服务新网关实战| 学习笔记
下一篇
oss创建bucket