首页 > 其他分享 >SpringBoot整合cache缓存入门

SpringBoot整合cache缓存入门

时间:2023-06-19 19:01:33浏览次数:38  
标签:缓存 SpringBoot cache springframework student import org public

目的:缓存可以通过将经常访问的数据存储在内存中,减少底层数据源如数据库的压力,从而有效提高系统的性能和稳定性。

一、启用缓存@EnableCaching 

我们需要在启动类上添加注解@EnableCaching来开启缓存功能。 

示例代码如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
// 开启缓存功能
@EnableCaching
public class MySpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

二、缓存的使用之@Cacheable

开启缓存后,我们可以使用@Cacheable、@CachePut、@CacheEvict注解来使用缓存。

@Cacheable:该注解可以将方法运行的结果直接进行缓存,在缓存有效期内再次调用该方法时不会调用方法本身,而是直接从缓存中获取结果并返回给调用方。

属性名

描述

value/cacheNames

指定缓存的名称

key

缓存数据时key的值,默认使用方法的参数值


keyGenerator

缓存的key生成策略(和key只能二选一)

cacheManager

指定的缓存管理器(Redis等)

cacheResolver

作用和cacheManager属性一样,也是只能二选一

condition

指定的缓存条件 (满足才会去缓存)

unless

如果满足unless指定条件,方法不进行缓存

sync

是否使用异步方式进行缓存 默认为false

@Cacheable测试:

1.添加依赖和项目配置文件

<!--jpa-->
<dependency>
  <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--lombok-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>
 <!--mysql-->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
# jpa使用update模式配置数据库
spring.jpa.hibernate.ddl-auto=update
# 显示数据执行语句
spring.jpa.show-sql=true
  
 #数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mydb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true

我们使用jpa的方式创建数据处理层。

2.创建数据实体

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author qx
 * @date 2023/06/19
 * @desc 数据实体
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "t_student")
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 姓名
     */
    @Column
    private String name;

    /**
     * 年龄
     */
    @Column
    private Integer age;

}

3.创建数据访问层

import com.example.myspringboot.bean.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student,Long> {
}

4.创建服务层

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author qx
 * @date 2023/06/19
 * @desc 服务层
 */
@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(value = "student")
    public List<Student> getAllStudent(){
        return studentRepository.findAll();
    }
}

5.创建测试控制器

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.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.RestController;

import java.util.List;

/**
 * @author qx
 * @date 2023/06/19
 * @desc
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/all")
    public List<Student> getAllStudent(){
        return studentService.getAllStudent();
    }
}

6.启动项目,访问请求接口

SpringBoot整合cache缓存入门_spring

2023-06-19 17:49:45.768  INFO 10012 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 17:49:45.768  INFO 10012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-19 17:49:45.769  INFO 10012 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_, student0_.age as age2_0_, student0_.name as name3_0_ from t_student student0_

看到控制台打印了sql执行语句。我们再次访问这一个接口,并把浏览器的消息清除。

SpringBoot整合cache缓存入门_spring_02

继续查询到了数据,但是控制台的sql语句并没有执行,从而实现了从缓存中获取数据。

三、缓存的使用之@CachePut

@CachePut:标注该注解的方法,在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果写入到指定的缓存中。一般用于更新缓存。

服务层:

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author qx
 * @date 2023/06/19
 * @desc 服务层
 */
@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(value = "student")
    public Student getStudent() {
        return studentRepository.findById(1L).get();
    }

    /**
     * 修改数据并写入到指定的缓存
     */
    @CachePut(value = "student")
    public Student updateStudent() {
        Optional<Student> studentOptional = studentRepository.findById(1L);
        Student student = studentOptional.get();
        student.setName("test2");

        // 修改数据
        studentRepository.save(student);

        return student;
    }
}

控制层:

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.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.RestController;


/**
 * @author qx
 * @date 2023/06/19
 * @desc
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/one")
    public Student getStudent() {
        return studentService.getStudent();
    }

    @GetMapping("/update")
    public Student updateStudent() {
        return studentService.updateStudent();
    }
}

测试:

SpringBoot整合cache缓存入门_缓存_03

2023-06-19 18:08:56.936  INFO 8064 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:08:56.936  INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:08:56.937  INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?
Hibernate: update t_student set age=?, name=? where id=?

我们重新查询数据,发现没有执行sql语句,但是查询使用了更新后的缓存数据。

SpringBoot整合cache缓存入门_缓存_04

2023-06-19 18:08:56.936  INFO 8064 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:08:56.936  INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:08:56.937  INFO 8064 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?
Hibernate: update t_student set age=?, name=? where id=?

四、缓存的使用之@CacheEvict

标注了@CacheEvict注解的方法被调用的时候,会从缓存中移除已存储的数据,这个注解一般用于删除缓存数据。

属性名

描述

value/cacheNames

缓存的名称

key

缓存的键

allEntries

是否根据缓存名称清空所有的缓存数据,默认为false,当为true时,将忽略注解上指定的key属性

beforeInvocation

是否在方法执行之前就清空缓存 默认为false

服务层:

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.repository.StudentRepository;
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 java.util.Optional;

/**
 * @author qx
 * @date 2023/06/19
 * @desc 服务层
 */
@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(value = "student")
    public Student getStudent() {
        return studentRepository.findById(1L).get();
    }

    /**
     * 修改数据并写入到指定的缓存
     */
    @CachePut(value = "student")
    public Student updateStudent() {
        Optional<Student> studentOptional = studentRepository.findById(1L);
        Student student = studentOptional.get();
        student.setName("test2");

        // 修改数据
        studentRepository.save(student);

        return student;
    }

    /**
     * 清除缓存
     */
    @CacheEvict(value = "student")
    public void deleteCache() {
        System.out.println("清除缓存");
    }
}

控制层:

import com.example.myspringboot.bean.Student;
import com.example.myspringboot.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.RestController;


/**
 * @author qx
 * @date 2023/06/19
 * @desc
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/one")
    public Student getStudent() {
        return studentService.getStudent();
    }

    @GetMapping("/update")
    public Student updateStudent() {
        return studentService.updateStudent();
    }

    @GetMapping("/clearCache")
    public void clearCache(){
        studentService.deleteCache();
    }
}

先调用清除缓存的接口,再访问查询接口。

SpringBoot整合cache缓存入门_数据_05

SpringBoot整合cache缓存入门_数据_06

控制台显示:

2023-06-19 18:22:12.955  INFO 6440 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-19 18:22:12.956  INFO 6440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-19 18:22:12.957  INFO 6440 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
清除缓存
Hibernate: select student0_.id as id1_0_0_, student0_.age as age2_0_0_, student0_.name as name3_0_0_ from t_student student0_ where student0_.id=?

我们从控制台可以看到清除缓存后,再次请求查询的接口会重新执行查询的sql语句。

标签:缓存,SpringBoot,cache,springframework,student,import,org,public
From: https://blog.51cto.com/u_13312531/6516922

相关文章

  • Mongodb 缓存页结构, 为什么我那么快 (1)
    MONGODB数据库写入和并发的速度,绝非是传统数据库可以比拟的,但到底为什么插入的速度这么快,和他的数据库引擎wiredTiger有关,那么就看看MONGODBwiredTiger的设计。MONGODB的数据库引擎WiredTiger, 使用PAGE页的方式,来存储数据,但是磁盘和内存的页面的结构是不一致的,内存的页面......
  • SpringBoot WebUploader 分块上传
    ​ 我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用。这次项目的需求:支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,ie8,ie9,Chrome,Firefox,360安全浏览器,并且刷新浏览器后仍然能够续传,重启浏览器(关闭......
  • SpringBoot整合JustAuth部分代码
    SpringBoot整合JustAuth部分代码gitee:ttt项目1.1、思路一、前端:gitee、github、qq图标链接二、后端1、导入相关:依赖(maven项目)2、写两个接口: 2-1:根据(用户ID、回调URL)获取(授权码) 2-2:根据(用户ID、用户秘钥、回调URL、授权码)获取token(并)获取(用户信息)......
  • springboot启动流程 (2) 组件扫描
    SpringBoot的组件扫描是基于Spring@ComponentScan注解实现的,该注解使用basePackages和basePackageClasses配置扫描的包,如果未配置这两个参数,Spring将扫描该配置类所属包下面的组件。在服务启动时,将使用ConfigurationClassPostProcessor扫描当前所有的BeanDefinition,解析Configur......
  • Datagridview双缓存
    PrivateSubDLG_Load(senderAsObject,eAsEventArgs)HandlesMe.LoadDataGridView1.GetType.InvokeMember("DoubleBuffered",System.Reflection.BindingFlags.NonPublic_......
  • springboot第26集:centos,docker
    yum-vLoading"fastestmirror"pluginLoading"langpacks"pluginLoading"product-id"pluginLoading"search-disabled-repos"pluginLoading"subscription-manager"pluginAddingen\_US.UTF-8tolanguageli......
  • LRU(最近最少使用) 缓存题与该算法思路
    题:https://leetcode.cn/problems/lru-cache/description/请你设计并实现一个满足LRU(最近最少使用)缓存约束的数据结构。实现LRUCache类:LRUCache(intcapacity)以正整数作为容量capacity初始化LRU缓存intget(intkey)如果关键字key存在于缓存中,则返回关键字......
  • [Web] Cache Directives
     no-cache:validatecacheasthelatestonebeforeusingit.Thismeansthatacacheshouldnotserveastoredcopyoftheresponsewithoutvalidatingitsfreshnesswiththeserver.Theresponsecanbestoredinacache,butitmustcheckwiththeserver......
  • springboot中操作redis
    1.maven引入相关依赖<dependencies> <!--spring-boot-starter-data-redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId&g......
  • SpringBoot:SpringWeb项目+Vue项目dist包整合成jar包
    接到需求做一个小功能项目,其中还要配备前端页面,并且将前端打包进后端jar包内,由jar包运行。项目结构将Vue打包之后的dist文件放到resouces资源路径下修改pom文件将下面的build配置替换掉pom中的build<build><finalName>自定义项目jar名称(可以用${project.artifatId})</finalNam......