首页 > 其他分享 >SpringBoot整合Cache缓存深入理解

SpringBoot整合Cache缓存深入理解

时间:2023-06-20 16:01:08浏览次数:59  
标签:缓存 SpringBoot Cache student0 _. student import id

我们在上一篇的基础上继续学习。

SpringBoot整合cache缓存入门

一、@Caching注解

@Caching注解用于在方法或者类上,同时指定多个Cache相关的注解。

属性名

描述

cacheable

用于指定@Cacheable注解

put

用于指定@CachePut注解

evict

用于指定@CacheEvict注解

示例代码如下:

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.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.Optional;

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

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(value = "student", key = "#id")
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

   @Caching(cacheable = {@Cacheable(value = "student", key = "#student.id")}, put = {@CachePut(value = "student", key = "#student.id")})
    public Student saveStudent(Student student) {
        studentRepository.save(student);
        return student;
    }
}

在saveStudent方法中,@Caching注解中使用了cacheable属性和put属性,该方法先是使用@Cacheable注解查询缓存缓存,然后再使用@CachePut注解把缓存存储到指定的key中。

控制层代码:

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.PathVariable;
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("/{id}")
    public Student getStudent(@PathVariable Long id) {
        return studentService.getStudent(id);
    }

    @GetMapping("/save")
    public Student updateStudent(Student student) {
        return studentService.saveStudent(student);
    }
}

测试:

SpringBoot整合Cache缓存深入理解_清除缓存

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=?

我们调用新增的方法,先是清除了缓存然后再添加到缓存。

SpringBoot整合Cache缓存深入理解_清除缓存_02

我们再次请求查询数据接口发现控制台没有执行sql语句

SpringBoot整合Cache缓存深入理解_spring_03

二、@CacheConfig注解

@CacheConfig注解可以把一些缓存配置提取到类级别的一个地方,这样我们就不必在每个方法都设置相关的配置。

我们之前设置缓存可以使用如下代码:

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


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

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(value = "student", key = "#id")
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

    @CachePut(value = "student", key = "#student.id")
    public Student saveStudent(Student student) {
        studentRepository.save(student);
        return student;
    }

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

然后我们使用@CacheConfig配置公共的缓存变量。

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


/**
 * @author qx
 * @date 2023/06/19
 * @desc 服务层
 */
@Service
@CacheConfig(cacheNames = {"student"})
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(key = "#id")
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

    @CachePut(key = "#student.id")
    public Student saveStudent(Student student) {
        studentRepository.save(student);
        return student;
    }

    /**
     * 清除缓存
     */
    @CacheEvict(key = "#id")
    public void deleteCache(Long id) {
        System.out.println("清除缓存");
    }
}

测试后发现效果是一样的。

三、condition&unless属性

condition:指定缓存的条件,满足什么条件才缓存。

unless: 否定缓存,当满足unless条件时,方法的结果不就行缓存。

// ID大于0才会进行缓存 
@Cacheable(key = "#id", condition = "#id>0")
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

四、allEntries&beforeInvocation属性

这两个属性都可以清除全部缓存数据,不过allEntries是方法调用后清理,beforeInvocation是方法调用前清理。

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

/**
 * @author qx
 * @date 2023/06/19
 * @desc 服务层
 */
@Service
@CacheConfig(cacheNames = {"student"})
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    @Cacheable(key = "#id", condition = "#id>0")
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

    @CachePut(key = "#student.id")
    public Student saveStudent(Student student) {
        studentRepository.save(student);
        return student;
    }

    /**
     * 清除所有缓存
     */
    @CacheEvict(allEntries = true)
    public void deleteCache() {
        System.out.println("清除缓存");
    }
}

SpringBoot整合Cache缓存深入理解_spring_04

清除所有缓存并查询两个数据并缓存

清除缓存
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: 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缓存深入理解_spring_05

清除缓存
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: 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: 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=?

五、集成Redis实现缓存

1.添加依赖

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

2.配置Redis做为缓存管理器

#设置缓存类型,这里使用Redis作为缓存服务器
spring.cache.type=redis


标签:缓存,SpringBoot,Cache,student0,_.,student,import,id
From: https://blog.51cto.com/u_13312531/6523491

相关文章

  • SpringBoot02
    Springboot021.Springboot注册三大组件Servlet、Filter、Listener三大组件和我们之前学习的web阶段中Servlet、Filter、Listener一样servlet是一种运行服务器端的java应用程序,具有独立于平台和协议的特性,并且可以动态的生成web页面,它工作在客户端请求与服务器响应的中间层......
  • 缓存方案之Redis
    Redis简介  Redis是RemoteDictionaryServer(Redis)的缩写,或许光听名字你就能猜出它大概是做什么的。不错,它是一个由SalvatoreSanfilippo编写的key-value存储系统,是一个使用ANSIC语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型的Key-Value数据库,并提供多种......
  • Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离
    Docker配置SpringBoot+ShardingJDBC+MybatisPlus项目实现分库分表与读写分离 分类于 实战例子本文ShardingJDBC相关知识主要参考自ShardingJDBC官方文档,更多的用法建议到官网文档查看。前言传统的业务系统都是将数据集中存储至单一数据节点的解决方案,如今随着互联网数据......
  • [20230616]One Deadlock of 'row cache lock' and 'library cache lock'.txt
    [20230616]OneDeadlockof'rowcachelock'and'librarycachelock'.txt--//链接http://ksun-oracle.blogspot.com/2023/06/one-deadlock-of-row-cache-lock-and.html演示一个有趣的测试.--//他测试采用cluster表,我估计普通表这样操作不会出现这样的情况,先重复作者的测试看......
  • SpringBoot整合cache缓存入门
    目的:缓存可以通过将经常访问的数据存储在内存中,减少底层数据源如数据库的压力,从而有效提高系统的性能和稳定性。一、启用缓存@EnableCaching 我们需要在启动类上添加注解@EnableCaching来开启缓存功能。 示例代码如下:importorg.springframework.boot.SpringApplication;impor......
  • 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_......