Spring Cache 介绍
  BCkntiJu7RTL 26天前 28 0

Spring Cache 是 Spring 提供的的缓存解决方案,它并非是一个具体的缓存实现,而是和 JSR107 类似的一套缓存规范,基于注解并与 Spring 的无缝集成。本文主要介绍其基本概念及简单使用。

1、简介

1.1、Spring Cache 概述

Spring Cache 是 Spring 提供的一种缓存抽象机制,用于简化应用中的缓存操作。它通过将方法的返回值缓存起来,当下次调用同一方法时,如果传入的参数与之前的调用相同,就可以直接从缓存中获取结果,而不需要再执行方法体中的代码,提高了系统的性能和响应速度。

Spring Cache 的特点:
声明式缓存:通过在方法上添加注解,如 @Cacheable、@CachePut、@CacheEvict 等来声明缓存的行为,无需手动编写缓存代码。
多种缓存支持:Spring Cache 提供了对多种缓存框架的支持,包括 Redis、Ehcache、Guava Cache、Caffeine 等,可以根据需要选择合适的缓存实现。
缓存策略配置:可以通过配置文件或者编程方式来配置缓存的策略,包括缓存的过期时间、缓存的淘汰策略等。
注解灵活应用:通过在方法上添加不同的注解,可以实现缓存的读取、更新和清除等操作,根据业务需求进行灵活配置。
缓存切面自动代理:Spring Cache 通过 AOP 技术,利用代理模式在方法执行前后拦截,自动处理缓存相关的操作,对业务代码无侵入。

1.2、Spring Cache 注解

注解 说明
@Cacheable 标记在方法上,表示方法的返回值会被缓存。当方法被调用时,会先检查缓存中是否存在对应的结果,如果存在,则直接返回缓存中的值,如果不存在,则执行方法体,并将返回值缓存起来。
@CachePut 标记在方法上,表示方法的返回值会被缓存。不同于 @Cacheable,@CachePut 每次都会执行方法体,并将返回值缓存起来;它通常用于更新缓存。
@CacheEvict 标记在方法上,表示清除缓存项。通过设置不同的属性来清除的相应缓存项,通过 key 属性来清除特定键的缓存项,通过 allEntries 属性来清除所有缓存项。
@Caching 用于多个缓存操作的组合,可以同时使用 @Cacheable、@CachePut 和 @CacheEvict 等注解。
@CacheConfig 标记在类上,用于指定该类中所有方法的缓存相关配置,包括缓存名称、缓存管理器等。

这些注解通过声明式的方式来管理缓存,通过在方法上添加相应的注解,可以方便地实现缓存的读取、更新和清除等操作。同时,Spring Cache 还支持使用 SpEL 表达式来动态地指定缓存的 Key 和条件等。开发者可以根据具体的业务需求选择合适的注解来配置缓存行为。

2、Spring Cache 使用

Spring Boot 中使用 Spring Cache 大概有以下步骤。

2.1、引入相关依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.18</version>
    <relativePath />
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
</dependencies>

2.2、启用缓存

在启动类上添加 @EnableCaching 注解。

@SpringBootApplication
@EnableCaching
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2.3、引入并配置具体的缓存实现

2.3.1、Caffeine 作为缓存实现

A、引入依赖

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

B、配置缓存(application.yml)

spring:
  cache:
    type: caffeine
    caffeine:
      spec: maximumSize=1000,expireAfterWrite=3s

spec 的配置属性可参考 com.github.benmanes.caffeine.cache.CaffeineSpec 类。

2.3.2、JCache 作为缓存实现

JCache 也是缓存规范,这里使用 Ehcache3 作为其缓存实现。

A、引入依赖

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

B、配置缓存(application.yml)

spring:
  cache:
    type: jcache
    jcache:
      config: classpath:ehcache3.xml

C、ehcache3 配置(ehcache3.xml)

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xmlns="http://www.ehcache.org/v3"
        xsi:schemaLocation="http://www.ehcache.org/v3
        http://www.ehcache.org/schema/ehcache-core-3.10.xsd
        http://www.ehcache.org/v3/jsr107
        http://www.ehcache.org/schema/ehcache-107-ext-3.10.xsd">

    <persistence directory="D:\temp"/>

    <cache alias="myCache">
        <key-type>java.lang.Integer</key-type>
        <value-type>java.lang.String</value-type>
        <expiry>
            <tti unit="minutes">5</tti>
        </expiry>
        <resources>
            <heap unit="MB">10</heap>
            <offheap unit="MB">50</offheap>
            <disk persistent="true" unit="MB">500</disk>
        </resources>
    </cache>
</config>

2.4、缓存使用

根据需要在方法上添加相应注解即可。

package com.abc.general.service.impl;

import com.abc.general.service.ICacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CacheServiceImpl implements ICacheService {
    @Cacheable(cacheNames = "myCache", key = "#id")
    @Override
    public String queryById(int id) {
        log.info("queryById,id={}", id);
        return "value" + id;
    }

    @CachePut(cacheNames = "myCache", key = "#id")
    @Override
    public String updateById(int id, String newValue) {
        log.info("updateById,id={},newValue={}", id, newValue);
        return newValue;
    }

    @CacheEvict(cacheNames = "myCache", key = "#id")
    @Override
    public void deleteById(int id) {
        log.info("deleteById,id={}", id);
    }
}

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 26天前 0

暂无评论

推荐阅读
  bVJlYTdzny4o   9天前   21   0   0 Java
BCkntiJu7RTL