飞不高 发表于 2024-5-17 23:01:21

Spring Cache 先容

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=3sspec 的设置属性可参考 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.xmlC、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);
    }


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Spring Cache 先容