Spring Cache简介与入门案例

Spring Cache简介与使用

SpringCache简介

Spring Cache 是 Spring 框架提供的一个缓存抽象层,它旨在简化缓存的使用,同时支持多种缓存实现(如 EhCache、Redis、Caffeine 等)。通过 Spring Cache,开发者可以轻松地将缓存功能集成到应用程序中,而无需手动管理缓存的存储和检索逻辑。
核心概念
Spring Cache 的核心概念包括以下几个部分:

缓存管理器(CacheManager)

缓存管理器是 Spring Cache 的核心组件之一,它负责管理缓存的生命周期,包括创建、销毁和访问缓存。不同的缓存实现(如 EhCache、Redis 等)会有对应的CacheManager实现。

例如:

  • 如果使用 EhCache,CacheManager会与 EhCache 的配置文件(ehcache.xml)交互。
  • 如果使用 Redis,CacheManager会与 Redis 客户端进行通信。

缓存(Cache)

缓存是存储数据的地方,它通常是一个键值对的集合。Spring Cache 提供了Cache接口,不同的缓存实现会提供具体的实现类。
• 例如:
• EhCache 使用EhCache类实现。
• Redis 使用RedisCache类实现。

缓存注解

Spring Cache 提供了一系列注解,用于声明缓存的行为。这些注解可以直接添加到方法上,从而实现缓存的读取、写入和清除等操作。

常用注解

注解说明
@EnableCaching启用 Spring Cache 的注解支持。这是使用 Spring Cache 的前提条件,必须在配置类或主类上添加该注解。
@Cacheable用于声明方法的返回值可以被缓存。如果缓存中已经存在数据,则直接返回缓存值,而不会执行方法体。
@CachePut用于更新缓存值。无论缓存中是否存在数据,都会执行方法体,并将方法的返回值更新到缓存中。
@CacheEvict用于清除缓存。可以清除单个缓存或整个缓存。

入门案例

准备工作
  1. 创建数据库
    CREATE UPDATE springcachedemo
    CREATE TABLE user (
    id bigint NOT NULL AUTO_INCREMENT,
    name varchar(45) DEFAULT NULL,
    age int DEFAULT NULL,
    PRIMARY KEY (id)
    );

  2. 导入maven坐标

<?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.7.3</version>
        <relativePath/>
    </parent>
    <groupId>com.nie</groupId>
    <artifactId>springcache-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.3</version>
            </plugin>
        </plugins>
    </build>
</project>

  1. 开启缓存注解
package com.nie;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@Slf4j
@SpringBootApplication
@EnableCaching//开始缓存注解
public class CacheDemoApplication {
   public static void main(String[] args) {
       SpringApplication.run(CacheDemoApplication.class,args);
       log.info("项目启动成功...");
   }
}
测试@CachePut
package com.nie.controller;

import com.nie.entity.User;
import com.nie.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.web.bind.annotation.*;

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

    @Autowired
    private UserMapper userMapper;

    /**
     * 如果使用spring cache缓存数据,key的生成:CacheNames::key
     * key 的值在这里使用spring EL表达式 或者 #result.id 或者 #p0.id 或者 #a0.id 等等等等
     * @param user
     * @return
     */
    @PostMapping
    @CachePut(cacheNames = "UserCache",key = "#user.id") //UserCache::1
    //@CachePut(cacheNames = "UserCache",key = "#result.id")  对象导航
    //@CachePut(cacheNames = "UserCache",key = "#p0.id") 取第一个参数
    //@CachePut(cacheNames = "UserCache",key = "#a0.id") 取第一个参数
    public User save(@RequestBody User user){
        userMapper.insert(user);
        return user;
    }
package com.nie.mapper;

import com.nie.entity.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper{

    @Insert("insert into user(name,age) values (#{name},#{age})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    void insert(User user);
  }

用postman发送请求

在这里插入图片描述
请求之后数据库增加
在这里插入图片描述
结果存入redis中了
在这里插入图片描述

测试@Cacheable

package com.nie.controller;

import com.nie.entity.User;
import com.nie.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

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

    @Autowired
    private UserMapper userMapper;
    @DeleteMapping
    @CacheEvict(cacheNames = "UserCache",key = "#id") //UserCache::1
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }
package com.nie.mapper;

import com.nie.entity.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper{

    @Delete("delete from user where id = #{id}")
    void deleteById(Long id);

用postman发送请求
在这里插入图片描述
数据库中的数据被清除
在这里插入图片描述

redis中的数据被清除
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值