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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 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月前
|
缓存 并行计算 监控
vLLM 性能优化实战:批处理、量化与缓存配置方案
本文深入解析vLLM高性能部署实践,揭秘如何通过continuous batching、PagedAttention与前缀缓存提升吞吐;详解批处理、量化、并发参数调优,助力实现高TPS与低延迟平衡,真正发挥vLLM生产级潜力。
409 0
vLLM 性能优化实战:批处理、量化与缓存配置方案
|
1月前
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
1月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
354 2
|
1月前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
2月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
189 1
Redis专题-实战篇二-商户查询缓存
|
2月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
1842 1
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
478 0
|
1月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
|
1月前
|
缓存 运维 监控
Redis 7.0 高性能缓存架构设计与优化
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Redis 7.0高性能缓存架构,探索函数化编程、多层缓存、集群优化与分片消息系统,用代码在二进制星河中谱写极客诗篇。
下一篇
oss云网关配置