Spring Cache简单介绍和使用

news2024/9/21 2:39:24

目录

一、简介

二、使用默认ConcurrentMapManager 

(一)创建数据库和表

(二)创建boot项目

(三)使用Api

1、@EnableCaching

2、@CachePut

3、@cacheable

4、@CacheEvict

三、使用redis作为cache


一、简介

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。

Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。
CacheManager是Spring提供的各种缓存技术抽象接口
针对不同的缓存技术需要实现不同的CacheManager:

CacheManager默认使用的ConcurrentMapManager 

Spring Cache 常用注解

 在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 spring cache的基本api在web下的context包中

 如果有使用其他的api可以导入cache的依赖

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

二、使用默认ConcurrentMapManager 

(一)创建数据库和表

创建cache_demo数据库,并创建user表

> create database cache_demo;
Query OK, 1 row affected (0.02 sec)

> use cache_demo;
Database changed

> create table user (
> id bigint primary key,
> name varchar(50),
> age int,
> address varchar(50)
>);

 

 (二)创建boot项目

改POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.itheima</groupId>
    <artifactId>cache_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.5</version>
            </plugin>
        </plugins>
    </build>
</project>

 写YML

server:
  port: 8080
spring:
  application:
    #应用的名称,可选
    name: cache_demo
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: root
mybatis-plus:
  configuration:
    #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

User

@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;

    private String name;

    private int age;

    private String address;

}


UserMapper
====================================================
@Mapper
public interface UserMapper extends BaseMapper<User>{
}


UserController
====================================================
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    
    // 增加User
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }


    // 删除User
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

    // 更新User
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

    // 根据id查询User
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

    // 根据id和name查询User集合
    @GetMapping("/list")
    public List<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}

 主启动类

@Slf4j
@SpringBootApplication
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}

 (三)使用Api

1、@EnableCaching

启动类上加注解@EnableCaching  // 使用spring cache

2、@CachePut

    // 在controller中加入缓存对象
    @Autowired
    private CacheManager cacheManager;

    /**
     * CachePut:将方法返回值放入缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    @CachePut(value = "userCache",key = "#user.id")
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

通过ctrl点进key下载源码后我们可以看到这里使用的是SpEL语言动态获取值

 

测试,使用 postman 发请求 

 

 

 第一次添加会将返回的user存放进cacheManager中

 

3、@cacheable

在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
    /**
     * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * condition:条件,满足条件时才缓存数据
     * unless:满足条件则不缓存
     */
    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

测试,我们使用jack的id去查询一下,同样使用postman,在这个方法设置断点,如果没有触发断点说明是在cache中查询直接返回的

 4、@CacheEvict

    /**
     * CacheEvict:清理指定缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    @CacheEvict(value = "userCache",key = "#p0")
    //@CacheEvict(value = "userCache",key = "#root.args[0]")
    //@CacheEvict(value = "userCache",key = "#id")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

    //@CacheEvict(value = "userCache",key = "#p0.id")
    //@CacheEvict(value = "userCache",key = "#user.id")
    //@CacheEvict(value = "userCache",key = "#root.args[0].id")
    @CacheEvict(value = "userCache",key = "#result.id")
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

三、使用redis作为cache

导入redis依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

修改YML

server:
  port: 8080
spring:
  application:
    #应用的名称,可选
    name: cache_demo
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: 123456
  redis:
    host: 192.168.23.100
    port: 6379
    password: zjy123...000
    database: 1
  cache:
    redis:
      time-to-live: 1800000 #设置缓存过期时间,可选
mybatis-plus:
  configuration:
    #在映射实体或者属性时,将数据库中表名和字段名中的下划线去掉,按照驼峰命名法映射
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: ASSIGN_ID

启动项目后,cache变成了RedisCacheManager

 

使用postman发送save请求

db01

 发送DELETE删除缓存

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/393432.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

云计算基础——云计算认知

云计算的总体框架在服务方面&#xff0c;主要以提供用户基于云的各种服务为主&#xff0c;共包含3个层次:1.软件即服务&#xff08;Software as a Service&#xff0c;简称SaaS)&#xff0c;这层的作用是将应用主要以基于Web 的方式提供给客户;2.平台即服务(Platform as a Serv…

STL讲解——模拟实现vector

STL讲解——模拟实现vector vector深度剖析 在STL源码中&#xff0c;发现vector定义的并不是 start、size、capacity&#xff0c;而是start、finish、end_of_storage. 这样就可以得到size()和capacity()。 sizefinish-start capacityend_of_storage-start 扩容可能是本地扩容也…

Entity Framework简单使用

我喜欢比较老派的database first &#xff0c; 所以先创建sql server的数据库&#xff0c;比如dbname叫做&#xff1a;Blogging这里我省略了。 在visual studio里面创建一个控制台程序&#xff0c; 然后添加ado.net项目 选择“gen from database” 然后新建你的数据库连接&…

基于粒子群优化算法的分布式电源选址定容【IEEE33节点】(Matlab代码实现)

&#x1f468;‍&#x1f393;个人主页&#xff1a;研学社的博客&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5;&#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密…

测试人员须要知道的性能测试那些事

随着各企业的业务发展、用户量以及数据量的不断增加&#xff0c;系统承载的压力也会随之增加&#xff0c;服务系统的性能好坏又严重影响企业的利益。因此&#xff0c;性能测试重要性与需求越来越强烈。 常见的性能测试目的 性能测试是确定系统在特定工作负载下的稳定性和响应…

数智引航 共赢未来 | 科士达2023数据中心合作伙伴大会圆满召开!

3月5日&#xff0c;科士达2023年全国合作伙伴大会在广东深圳隆重召开&#xff0c;本次大会以“数智引航 共赢未来”为主题&#xff0c;来自全国各地的核心渠道伙伴齐聚一堂&#xff0c;深度交流&#xff0c;展望未来&#xff0c;共同探讨数据中心技术发展趋势&#xff0c;碰撞…

[Python图像处理] 使用高通滤波器实现同态滤波

使用高通滤波器实现同态滤波同态滤波基础实现同态滤波相关链接同态滤波基础 同态滤波是一种去除图像中乘性噪声的技术&#xff0c;常用于校正图像中的不均匀照明。根据图像形成的光照反射模型&#xff0c;图像 f(x,y)f(x,y)f(x,y) 可以由以下两个分量表征&#xff1a; 入射到…

linux中改变了jdk版本,为什么其他用户无法使用?

linux中改变了jdk版本&#xff0c;为什么其他用户无法使用&#xff1f; 1、jdk建在/usr/local目录下 2、环境变量写在/etc/profile下 3、如果发现root用户下&#xff0c;java -version可以出现版本信息&#xff0c;其他用户下查询不到jdk版本信息 问题&#xff1a;root用户下&…

关于递归处理,应该怎么处理,思路是什么?

其实问题很简单&#xff0c;就是想要循环遍历整个data对象&#xff0c;来实现所有name转成label&#xff0c;但是想到里面还有children属性&#xff0c;整个children里面可能还会嵌套很多很多的name&#xff0c;如此循环&#xff0c;很难搞&#xff0c;知道使用递归&#xff0c…

Linux系统安装Hbase,通过Zookeeper管理

目录 一、安装包解压&#xff0c;重命名 二、修改环境配置 2.1、修改 Hbase配置 2.2、修改 zookeeper配置 2.3、修改/etc/profile 环境&#xff0c;添加Hbase和Zookeeper环境路径 三、启动Hbase 四、退出服务 一、安装包解压&#xff0c;重命名 安装包&#xff1a;链接…

数据分析:基于随机森林(RFC)对酒店预订分析预测

数据分析&#xff1a;基于随机森林(RFC)对酒店预订分析预测 作者&#xff1a;AOAIYI 作者简介&#xff1a;Python领域新星作者、多项比赛获奖者&#xff1a;AOAIYI首页 &#x1f60a;&#x1f60a;&#x1f60a;如果觉得文章不错或能帮助到你学习&#xff0c;可以点赞&#x1f…

微信小程序上拉、下拉刷新组封装件

在开发小程序的时候通常会遇到上拉或者下拉刷新的功能需求&#xff0c;然而这个功能很多页面也都会用到&#xff0c;因此这里&#xff0c;把这个功能封装为组件&#xff0c;方便复用 我很直接&#xff0c;不多说&#xff0c;上代码 首先index.wxml <scroll-view scroll-y…

LNMP架构的源码编译环境下部署 Discuz!社区论坛与Wordpress博客

目录 一.编译安装Nginx 1.关闭防火墙 2.安装依赖包 3.创建运行用户 4.解压软件包并编译安装 5.软链接路径优化 6.添加Nginx系统服务 二.编译安装MySQL服务 1.安装依赖环境 2.创建运行用户 3.解压软件包并编译安装 4.数据库目录进行权限调整 5.修改配置文件 6.设…

linux面试基础篇

题目目录1.简述DNS分离解析的工作原理&#xff0c;关键配置2.apache有几种工作模式&#xff0c;分别简述两种工作模式及其优缺点&#xff1f;3.写出172.0.0.38/27 的网络id与广播地址4.写出下列服务使用的传输层协议&#xff08;TCP/UDP&#xff09;及默认端口5.在局域网想获得…

Uni-app页面路由的几种写法

uni.navigateTo( OBJECT) 保留当前页面&#xff0c;跳转到应用内的某个页面&#xff0c;使用 uni.navigateBack 可以返回到原来页面 ONJECT参数说明&#xff1a; 注意&#xff1a; 页面跳转路径有层级限制&#xff0c;不能无限跳转新页面跳转到 tabBar 页面只能使用 switchT…

NCRE计算机等级考试Python真题(十二)

第十二套试题1、以下关于程序设计语言的描述&#xff0c;错误的选项是&#xff1a;A.Python语言是一种脚本编程语言B.汇编语言是直接操作计算机硬件的编程语言C.程序设计语言经历了机器语言、汇编语言、脚本语言三个阶段D.编译和解释的区别是一次性翻译程序还是每次执行时都要翻…

LCD液晶段码屏显示驱动IC -VK2C23高抗干扰/抗噪,适用于瓦斯表/燃气表/煤气表

产品型号&#xff1a;VK2C23A/B产品品牌&#xff1a;永嘉微电/VINKA封装形式&#xff1a;LQFP64/48可定制&#xff1a;DICE(COB邦定片)&#xff1b;COG(邦定玻璃用)产品年份&#xff1a;新年份原厂 工程服务&#xff0c;技术支持&#xff01;VK2C23A/B概述&#xff1a;VK2C23A/…

微信小程序this指向问题

前言 最近在开发微信小程序时不时会遇到一个很奇怪的问题&#xff0c;有些情况下用 this.setData 可以改变视图显示&#xff0c;有些情况下使用 this.setData 无效&#xff0c;这又是为什么呢&#xff1f; 问题描述 在解释这个问题前&#xff0c;我们先来看两段代码&#xff1…

强烈推荐YouTube精选wxWidgets视频教程汇总

wxWidgets介绍 wxWidgets介绍 —— 一文全面了解wxWidgets_boomworks的博客-CSDN博客wxWidgets由爱丁堡大学的Julian Smart于1992年创立。最初是一个用于创建在Unix和Windows上可移植的应用程序的项目&#xff0c;后来它已成长为支持MacOS&#xff0c;GTK以及许多其他工具包和…

【Linux】-- 权限和Shell运行原理

目录 Shell的运行原理 用户切换 su - / su sudo 权限 chmod chown chgrp 八进制方法修改文件属性 目录权限 粘滞位 umask 自定义默认权限 Shell的运行原理 广义上&#xff0c;Linux发行版 Linux内核 外壳程序 Linux 从广义上来理解它是一个操作系统 而从狭义上…