当前位置: 首页 > news >正文

SpringBoot开发中如何缓存数据, 减少数据库的访问频率?

一:自定义是否开启缓存

方法一:

在不同环境的配置文件中如application-dev.yml、application-test.yml、application-prod.yml,修改 spring.cache.type = none;

spring:cache:type: none	

方法二:

自定义配置

application.yml:

## 开启数据缓存
caching:enabled: true

com.scaffold.test.config.CacheConfig

缓存配置文件

@Configuration
@EnableCaching
//配置文件读取是否启用此配置
@ConditionalOnProperty(prefix = "caching", name = "enabled", havingValue = "true")
public class CacheConfig {}

二:simpleCacheManage

simpleCacheManage 基于ConcurrentHashMap 实现,不依赖其他库,如果增加了注解@EnableCaching,默认开启缓存,可以通过设置cache-names限制缓存列表

1.设置缓存列表

application.yml

spring:cache:type: simplecache-names: cache1,cache2

2.添加maven依赖:

<!-- cache 依赖 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId>
</dependency>

3.使用注解

注意:所有的注解是加到实现类serviceImpl方法上的

注解描述
@Cacheable在方法执行前 Spring 先查看缓存中是否有数据,若有,则直接返回缓存数据;若无数据,调用方法将方法返回值放入缓存中
@CachePut无论怎样,都会将方法的返回值放到缓存中。
@CacheEvict将一条或多条数据从缓存中删除
@Caching可以通过 @Caching 注解组合多个注解策略在一个方法

@Cacheable、@CachePut、@CacheEvict 都有 value 属性,指定的是要使用的缓存名称;key 属性指定的是数据在缓存中存储的键

4.代码实现:

4.1配置类

package com.scaffold.test.config;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.time.Duration;/*** 缓存配置文件* 配置文件读取是否启用此配置* @author alex*/
@Configuration
@EnableCaching
@ConditionalOnProperty(prefix = "caching", name = "enabled", havingValue = "true")
public class CacheConfig {@Beanpublic CacheManager cacheManager() {return new ConcurrentMapCacheManager("cacheData");}}

4.2实体类

package com.scaffold.test.entity;import lombok.Data;
import lombok.EqualsAndHashCode;import java.io.Serializable;/*** @author alex wong*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Student implements Serializable {private static final long serialVersionUID=1L;private int id;private String name;private Integer age;}

4.3service层

package com.scaffold.test.service;import com.scaffold.test.entity.Student;
import com.baomidou.mybatisplus.extension.service.IService;import java.util.List;/*** <p>* 服务类* </p>** @author alex wong*/
public interface StudentService extends IService<Student> {List<Student> findAll();Student findStudent(Student student);Student testStudent(String text);void deleteStudent(Student student);void saveStudent(Student student);}

4.4service实现类

package com.scaffold.test.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scaffold.test.entity.Student;
import com.scaffold.test.mapper.StudentMapper;
import com.scaffold.test.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.List;/*** <p>*  服务实现类* </p>** @author alex wong*/@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {@Resourceprivate StudentMapper studentMapper;@Override@Cacheable(value = "cacheData")public List<Student> findAll(){return studentMapper.selectAll();}/*** 缓存查询数据* @Cacheable 缓存数据到缓存 student 中* 其中缓存名称为 student 数据的 key 是 student 的 id* @param student s* @return*/@Override@Cacheable(value = "cacheData", key = "#student.id")public Student findStudent(Student student) {log.warn("增加了student为{}的数据缓存", student);int id = student.getId();if(id == 0){return null;}return studentMapper.findStudent(student);}/*** 删除缓存* @CacheEvict 从缓存 student 中删除* 其中缓存名称为 student 数据的 key 是 student 的 id* @param student s*/@Override@CacheEvict(value = "cacheData", key = "#student.id")public void deleteStudent(Student student) {log.warn("删除了student为{}的数据缓存", student);}/*** @CachePut 缓存新增的或更新的数据到缓存* 其中缓存名称为 student 数据的 key 是 student 的 id* @param student*/@Override@CachePut(value = "cacheData", key = "#student.id")public void saveStudent(Student student) {log.warn("保存了id、key 为{}的数据缓存", student);studentMapper.insertStudent(student);}@Override@Cacheable(value = "cacheData", key = "#text")public Student testStudent(String text) {System.out.println("test" + text);Student student = new Student();student.setName(text);return student;}
}

 4.5dao层接口:

package com.scaffold.test.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.scaffold.test.entity.Student;import java.util.List;/*** <p>* Mapper 接口* </p>** @author alex wong*/
public interface StudentMapper extends BaseMapper<Student> {List<Student> selectAll();Student findStudent(Student student);int insertStudent(Student student);
}

4.6Mapper。xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.scaffold.test.mapper.StudentMapper"><!-- 通用查询映射结果 --><resultMap id="BaseResultMap" type="com.scaffold.test.entity.Student"><result column="id" property="id"/><result column="name" property="name"/><result column="age" property="age"/></resultMap><!-- 通用查询结果列 --><sql id="Base_Column_List">id,name, age</sql><sql id="Where_Condition"><where><if test="id != null and id != ''">id=#{id}</if><if test="name != null and name != ''">and name=#{name}</if><if test="age != null and age != ''">and age=#{age}</if></where></sql><insert id="insertStudent">insert student(id, name, age)values(#{id}, #{name}, #{age})</insert><select id="selectAll" resultMap="BaseResultMap">select * from student</select><select id="findStudent" resultType="com.scaffold.test.entity.Student">select * from student<include refid="Where_Condition"></include></select>
</mapper>

4.7sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (`id` int(11) NOT NULL,`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,`age` int(11) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '1', 2323);
INSERT INTO `student` VALUES (2, '2', 2323);
INSERT INTO `student` VALUES (3, '3', 2323);SET FOREIGN_KEY_CHECKS = 1;

4.8Controller层

package com.scaffold.test.controller;import com.scaffold.test.entity.Student;
import com.scaffold.test.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.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** <p>*  前端控制器* </p>** @author alex wong*/
@RestController
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("list")public List<Student> getAll(){return studentService.findAll();}@GetMapping("add")public void addStudent(Student student){studentService.saveStudent(student);}@GetMapping("find")public Student findStudent(Student student){return studentService.findStudent(student);}@GetMapping("delete")public void deleteStudent(Student student){studentService.deleteStudent(student);}@GetMapping("test")public Student test(@RequestParam String text){return studentService.testStudent(text);}
}

相关文章:

SpringBoot开发中如何缓存数据, 减少数据库的访问频率?

一&#xff1a;自定义是否开启缓存 方法一&#xff1a; 在不同环境的配置文件中如application-dev.yml、application-test.yml、application-prod.yml&#xff0c;修改 spring.cache.type none; spring:cache:type: none 方法二&#xff1a; 自定义配置 application.yml&…...

PostgreSQL如何在windows/linux开启归档

linux开启归档&#xff1a; archive_mode onarchive_command test ! -f /mnt/pg12/archivedir/%f && cp %p /mnt/pg12/archivedir/%fwindows开启归档&#xff1a; archive_mode onarchive_command copy "%p" "C:\\server\\pg12\\archivedir\\%f&q…...

【启明智显分享】基于国产Model3芯片的7寸触摸屏助力智慧医疗,电子床头屏提升护理交互

未来医院必然是以信息化为基础&#xff0c;以物联网为特征&#xff0c;以医疗为核心的服务型医院。病房作为医院的重要服务场所&#xff0c;成为智慧医院建设的重要一环。 为提高医护人员与患者的互动交流&#xff0c;给医疗注入智慧元素&#xff0c;让患者享受智能服务&#…...

从理论到实践:如何用 TDengine 打造完美数据模型​

在用 TDengine 进行数据建模之前&#xff0c;我们需要回答两个关键问题&#xff1a;建模的目标用户是谁&#xff1f;他们的具体需求是什么&#xff1f;在一个典型的时序数据管理方案中&#xff0c;数据采集和数据应用是两个主要环节。如下图所示&#xff1a; 对于数据采集工程师…...

可以免费合并pdf的软件 合并pdf文件的软件免费 合并pdf的软件免费

在数字化办公的今天&#xff0c;pdf格式因其稳定性和跨平台兼容性被广泛使用。然而&#xff0c;当我们需要将多个 pdf 文件合并为一个时&#xff0c;却往往感到力不从心。本文将为你介绍几款强大的pdf文件合并软件&#xff0c;让你轻松管理文档。 方法一、使用pdf转换器 步骤1…...

【排序 滑动窗口 】1498. 满足条件的子序列数目

本文涉及至知识点 排序 C算法&#xff1a;滑动窗口总结 LeetCode1498. 满足条件的子序列数目 给你一个整数数组 nums 和一个整数 target 。 请你统计并返回 nums 中能满足其最小元素与最大元素的 和 小于或等于 target 的 非空 子序列的数目。 由于答案可能很大&#xff0c;…...

RabbitMQ普通集群搭建指南

RabbitMQ普通集群搭建指南 本文已经完全迁移至&#xff0c;www.geekery.cn 后续不在此更新 目标架构 本次搭建的目标是构建一个由三个节点组成的RabbitMQ集群&#xff0c;节点信息如下&#xff1a; rabbit02: IP地址 192.168.10.132rabbit03: IP地址 192.168.10.133rabbit04:…...

AGV平面坐标系变换公式及实例

1、AGV坐标系简介 如上图&#xff0c;小车前后对角是有激光雷达的&#xff0c;其坐标系称为激光坐标系&#xff0c;采用极坐标系体现。中间为车体坐标系&#xff0c;激光坐标系相对于车体坐标系关系不变&#xff1b;左下角是地图坐标系&#xff0c;小车扫图后&#xff0c;建立的…...

es切片和集群

解决单点故障 支持高并发 解决海量数据 1.cluster 集群&#xff1a;包含多个节点&#xff0c;每个节点属于哪个集群是通过一个集群名称&#xff08;集群名称&#xff0c;默认是elasticsearch&#xff09;来决定的&#xff0c;对于中小型应用来说&#xff0c;刚开始一个集群就…...

IEEE官方列表会议 | 第三届能源与环境工程国际会议(CFEEE 2024)

会议简介 Brief Introduction 2024年第三届能源与环境工程国际会议(CFEEE 2024) 会议时间&#xff1a;2024年12月2日-4日 召开地点&#xff1a;澳大利亚凯恩斯 大会官网&#xff1a;CFEEE 2024-2024 International Conference on Frontiers of Energy and Environment Engineer…...

深度学习中的正则化技术 - Dropout篇

序言 在深度学习的浩瀚领域中&#xff0c;模型过拟合一直是研究者们面临的挑战之一。当模型在训练集上表现得近乎完美&#xff0c;却难以在未见过的数据&#xff08;测试集&#xff09;上保持同样优异的性能时&#xff0c;过拟合现象便悄然发生。为了有效缓解这一问题&#xf…...

《昇思 25 天学习打卡营第 18 天 | 扩散模型(Diffusion Models) 》

《昇思 25 天学习打卡营第 18 天 | 扩散模型&#xff08;Diffusion Models&#xff09; 》 活动地址&#xff1a;https://xihe.mindspore.cn/events/mindspore-training-camp 签名&#xff1a;Sam9029 扩散模型&#xff08;Diffusion Models&#xff09; 扩散模型概述 扩散模…...

【Django+Vue3 线上教育平台项目实战】Elasticsearch实战指南:从基础到构建课程搜索与数据同步接口

文章目录 前言一、Elasticsearch倒排索引 二、Docker 搭建 ESDocker 安装Docker 搭建 ES 三、ES基础语法创建索引查看索引删除索引添加数据查询数据修改数据删除数据条件查询分页查询排序 多条件查询andor 范围查询 四、ES在项目中的应用示例 前言 在数据驱动的时代&#xff0c…...

libtins初探-抓包嗅探

libtin 一、概述1. 可移植性2. 特性 二、基础知识1. PDU2. 地址类3. 地址范围类4. 网络接口5. 写pcap文件 三、嗅探1.嗅探基础2. 嗅探器配置3. 循环嗅探4. 使用迭代器嗅探6. 包对象7. 读取pcap文件8. 包的解析 四、发送包1. 发送网络层pdu2. 发送链路层pdu3. 发送和接收响应校验…...

大语言模型-Bert-Bidirectional Encoder Representation from Transformers

一、背景信息&#xff1a; Bert是2018年10月由Google AI研究院提出的一种预训练模型。 主要用于自然语言处理&#xff08;NLP&#xff09;任务&#xff0c;特别是机器阅读理、文本分类、序列标注等任务。 BERT的网络架构使用的是多层Transformer结构&#xff0c;有效的解决了长…...

bug诞生记——动态库加载错乱导致程序执行异常

大纲 背景问题发生问题猜测和分析过程是不是编译了本工程中的其他代码是不是有缓存是不是编译了非本工程的文件是不是调用了其他可执行文件查看CMakefiles分析源码检查正在运行程序的动态库 解决方案 这个案例发生在我研究ROS 2的测试Demo时发生的。 整体现象是&#xff1a;修改…...

Matlab演示三维坐标系旋转

function showTwo3DCoordinateSystemsWithAngleDifference() clear all close all % 第一个三维坐标系 origin1 [0 0 0]; x_axis1 [1 0 0]; y_axis1 [0 1 0]; z_axis1 [0 0 1];% 绕 x 轴旋转 30 度的旋转矩阵 theta_x 30 * pi / 180; rotation_matrix_x [1 0 0; 0 cos(th…...

redis的持久化机制以及集群模式

1.redis的持久化机制 内存数据库具有高速读写的优势&#xff0c;但由于数据存储在内存中&#xff0c;一旦服务器停止或崩溃&#xff0c;所有数据将会丢失。持久化机制的引入旨在将内存中的数据持久化到磁盘上&#xff0c;从而在服务器重启后能够恢复数据&#xff0c;提供更好的…...

【论文解读】大模型算法发展

一、简要介绍 论文研究了自深度学习出现以来&#xff0c;预训练语言模型的算法的改进速度。使用Wikitext和Penn Treebank上超过200个语言模型评估的数据集(2012-2023年)&#xff0c;论文发现达到设定性能阈值所需的计算大约每8个月减半一次&#xff0c;95%置信区间约为5到14个月…...

WebApi配置Swagger、Serilog、NewtonsoftJson、Sqlsugar、依赖注入框架Autofac、MD5加密

文章目录 项目准备1、创建WebApi项目配置Swagger、Serilog、NewtonsoftJsonNewtonsoftJsonSwaggerSerilog 使用ORM框架SqlSugar创建Service类库构成MVC框架使用AutoFac进行依赖注入 创建用户登录接口添加用户时进行安全防护 项目准备 1、创建WebApi项目 配置Swagger、Serilog…...

Mybatis逆向工程,动态创建实体类、条件扩展类、Mapper接口、Mapper.xml映射文件

今天呢&#xff0c;博主的学习进度也是步入了Java Mybatis 框架&#xff0c;目前正在逐步杨帆旗航。 那么接下来就给大家出一期有关 Mybatis 逆向工程的教学&#xff0c;希望能对大家有所帮助&#xff0c;也特别欢迎大家指点不足之处&#xff0c;小生很乐意接受正确的建议&…...

解决Ubuntu22.04 VMware失败的问题 ubuntu入门之二十八

现象1 打开VMware失败 Ubuntu升级之后打开VMware上报需要安装vmmon和vmnet&#xff0c;点击确认后如下提示 最终上报fail 解决方法 内核升级导致&#xff0c;需要在新内核下重新下载编译安装 查看版本 $ vmware -v VMware Workstation 17.5.1 build-23298084$ lsb_release…...

el-switch文字内置

el-switch文字内置 效果 vue <div style"color:#ffffff;font-size:14px;float:left;margin-bottom:5px;margin-right:5px;">自动加载</div> <el-switch v-model"value" active-color"#3E99FB" inactive-color"#DCDFE6"…...

生成 Git SSH 证书

&#x1f511; 1. ​​生成 SSH 密钥对​​ 在终端&#xff08;Windows 使用 Git Bash&#xff0c;Mac/Linux 使用 Terminal&#xff09;执行命令&#xff1a; ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" ​​参数说明​​&#xff1a; -t rsa&#x…...

拉力测试cuda pytorch 把 4070显卡拉满

import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试&#xff0c;通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小&#xff0c;增大可提高计算复杂度duration: 测试持续时间&#xff08;秒&…...

自然语言处理——循环神经网络

自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元&#xff08;GRU&#xff09;长短期记忆神经网络&#xff08;LSTM&#xff09…...

SAP学习笔记 - 开发26 - 前端Fiori开发 OData V2 和 V4 的差异 (Deepseek整理)

上一章用到了V2 的概念&#xff0c;其实 Fiori当中还有 V4&#xff0c;咱们这一章来总结一下 V2 和 V4。 SAP学习笔记 - 开发25 - 前端Fiori开发 Remote OData Service(使用远端Odata服务)&#xff0c;代理中间件&#xff08;ui5-middleware-simpleproxy&#xff09;-CSDN博客…...

【从零学习JVM|第三篇】类的生命周期(高频面试题)

前言&#xff1a; 在Java编程中&#xff0c;类的生命周期是指类从被加载到内存中开始&#xff0c;到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期&#xff0c;让读者对此有深刻印象。 目录 ​…...

android13 app的触摸问题定位分析流程

一、知识点 一般来说,触摸问题都是app层面出问题,我们可以在ViewRootImpl.java添加log的方式定位;如果是touchableRegion的计算问题,就会相对比较麻烦了,需要通过adb shell dumpsys input > input.log指令,且通过打印堆栈的方式,逐步定位问题,并找到修改方案。 问题…...

Vue ③-生命周期 || 脚手架

生命周期 思考&#xff1a;什么时候可以发送初始化渲染请求&#xff1f;&#xff08;越早越好&#xff09; 什么时候可以开始操作dom&#xff1f;&#xff08;至少dom得渲染出来&#xff09; Vue生命周期&#xff1a; 一个Vue实例从 创建 到 销毁 的整个过程。 生命周期四个…...