轻松搞定Spring集成缓存,让你的应用程序飞起来!

2023-09-22 14:26:09

在这里插入图片描述

主页传送门:📀 传送

  Spring 提供了对缓存的支持,允许你将数据存储在缓存中以提高应用程序的性能。Spring 缓存抽象基于 Java Caching API,但提供了更简单的编程模型和更高级的功能。
  Spring 集成缓存提供了一种方便的方式来使用缓存,从而提高应用程序的性能。Spring 缓存抽象提供了通用的缓存支持,并集成了常见的缓存解决方案。

缓存接口


  Spring 的缓存 API 以注解方式提供。Spring缓存接口定义主要由org.springframework.cache.Cache和org.springframework.cache.CacheManager两个接口完成。

  • org.springframework.cache.Cache:这个接口代表一个缓存组件,Spring框架通过这个接口与缓存交互。它有几个重要的方法:

    • String getName(): 返回缓存的名称。
    • Object get(Object key, Class<?> type): 根据key获取缓存数据,如果数据不存在,返回null。
    • void put(Object key, Object value): 向缓存中添加数据。
    • void evict(Object key): 根据key移除缓存数据。
    • void clear(): 清空缓存。
  • org.springframework.cache.CacheManager:这个接口定义了如何获取Cache实例。它有一个重要的方法:

    • Cache getCache(String name): 根据缓存的名称获取Cache实例。

  Spring通过这些接口与各种缓存实现(如EhCache,Redis,Hazelcast等)进行交互。要使用Spring的缓存功能,只需配置一个实现了CacheManager接口的Bean,然后在需要使用缓存的地方使用@Cacheable,@CacheEvict和@CachePut等注解即可。

开启注解


  Spring 为缓存功能提供了注解功能,但是你必须启动注解:
(1) 在 xml 中声明
  使用cache:annotation-driven/<cache:annotation-driven cache-manager=“cacheManager”/>
(2) 使用标记注解
   通过对一个类进行注解修饰的方式在这个类中使用缓存注解。

范例如下:

@Configuration
@EnableCaching
public class AppConfig {
}

缓存注解使用


  Spring 对缓存的支持类似于对事务的支持。 首先使用注解标记方法,相当于定义了切点,然后使用 Aop 技术在这个方法的调用前、调用后获取方法的入参和返回值,进而实现了缓存的逻辑。

@Cacheable


  表明所修饰的方法是可以缓存的:当第一次调用这个方法时,它的结果会被缓存下来,在缓存的有效时间内,以后访问这个方法都直接返回缓存结果,不再执行方法中的代码段。 这个注解可以用condition属性来设置条件,如果不满足条件,就不使用缓存能力,直接执行方法。 可以使用key属性来指定 key 的生成规则。

范例如下:

@Service  
public class ExampleService {  
  
    @Cacheable("examples")  
    public String getExample(String key) {  
        // 模拟一个耗时操作  
        try {  
            Thread.sleep(1000);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        return "Example for " + key;  
    }  
}

@CachePut


  与@Cacheable不同,@CachePut不仅会缓存方法的结果,还会执行方法的代码段。 当一个方法被标记为 @CachePut,Spring 会在该方法执行后更新缓存。它支持的属性和用法都与@Cacheable一致。

范例如下:

 @Service  
public class ExampleService {  
  
    @CachePut("examples")  
    public void updateExample(String key, String value) {  
        // 更新数据的操作  
        // ...  
    }  
}

@CacheEvict


  与@Cacheable功能相反,@CacheEvict表明所修饰的方法是用来删除失效或无用的缓存数据。当一个方法被标记为 @CacheEvict,Spring 会在该方法执行后从缓存中移除相关的数据。

范例如下:

@Service  
public class ExampleService {  
  
    @CacheEvict(value = "examples", key = "#id")  
    public void evictExample(String id) {  
        // 从缓存中移除数据的操作  
        // ...  
    }  
}

@Cacheable、@CacheEvict和@CachePut使用方法的集中展示示例:

@Service
public class UserService {
    // @Cacheable可以设置多个缓存,形式如:@Cacheable({"books", "isbns"})
    @Cacheable(value={"users"}, key="#user.id")
    public User findUser(User user) {
        return findUserInDB(user.getId());
    }

    @Cacheable(value = "users", condition = "#user.getId() <= 2")
    public User findUserInLimit(User user) {
        return findUserInDB(user.getId());
    }

    @CachePut(value = "users", key = "#user.getId()")
    public void updateUser(User user) {
        updateUserInDB(user);
    }

    @CacheEvict(value = "users")
    public void removeUser(User user) {
        removeUserInDB(user.getId());
    }

    @CacheEvict(value = "users", allEntries = true)
    public void clear() {
        removeAllInDB();
    }
}

@Caching


  如果需要使用同一个缓存注解(@Cacheable、@CacheEvict或@CachePut)多次修饰一个方法,就需要用到@Caching。

@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)

@CacheConfig


  与前面的缓存注解不同,这是一个类级别的注解。 如果类的所有操作都是缓存操作,你可以使用@CacheConfig来指定类,省去一些配置。

@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {
	@Cacheable
	public Book findBook(ISBN isbn) {...}
}

缓存存储


  Spring 允许通过配置方式接入多种不同的缓存存储。用户可以根据实际需要选择。

不同的缓存存储,具有不同的性能和特性。

使用 ConcurrentHashMap 作为缓存


示例配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

  <description>使用 ConcurrentHashMap 作为 Spring 缓存</description>
    <context:component-scan base-package="io.github.dunwu.spring.cache"/>

  <bean id="simpleCacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
      <set>
        <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>
        <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="users"/>
      </set>
    </property>
  </bean>

  <cache:annotation-driven cache-manager="simpleCacheManager"/>
</beans>

使用 Ehcache 作为缓存


示例配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

  <description>使用 EhCache 作为 Spring 缓存</description>

  <!--配置参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-store-configuration-->

  <context:component-scan base-package="io.github.dunwu.spring.cache"/>

  <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
  </bean>

  <bean id="ehcacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehcache"/>
  </bean>

  <cache:annotation-driven cache-manager="ehcacheCacheManager"/>
</beans>

ehcache.xml 中的配置内容完全符合 Ehcache 的官方配置标准。

使用 Caffeine 作为缓存


示例配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

  <description>使用 Caffeine 作为 Spring 缓存</description>

  <!--配置参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#cache-store-configuration-->

  <context:component-scan base-package="io.github.dunwu.spring.cache"/>

  <bean id="caffeineCacheManager" class="org.springframework.cache.caffeine.CaffeineCacheManager"/>

  <cache:annotation-driven cache-manager="caffeineCacheManager"/>
</beans>

参考资料

Spring 官方文档

在这里插入图片描述

  如果喜欢的话,欢迎 🤞关注 👍点赞 💬评论 🤝收藏  🙌一起讨论
  你的支持就是我✍️创作的动力!					  💞💞💞
更多推荐

从理解js双重递归执行顺序到用递归方式实现二叉树中序遍历

今天在学习力扣上94题二叉树的中序遍历时,js的实现方法之一是递归,但是函数内递归是双重,花了一些时间来理解双重递归调用的执行顺序。先看如下例子,参考文章(双递归的执行过程理解)示例代码如下:constfn=(n)=>{if(n>0){console.log('n1====',n)fn(n-1)console.log(

微软AIGC in a Day-探索人工智能与行业应用实践沙龙-参后感

先来看下宣传海报活动介绍总结活动主题:探索人工智能与行业应用实践沙龙微软PowerPlatform携手GPT,从应用层面深入AI+低代码开发,一场探索人工智能与行业应用实践的技术盛宴即将到来!9月16日,「探索人工智能与行业应用实践沙龙」,数位来自AI、低代码领域的技术专家,将通过**技术分享、案例实操等形式,带来AI

美国调查公司 Digital Discovery 利用OpenText Encase 调查取证工具发现隐藏在数据中的事实

美国调查公司依靠OpenTextEnCase来分析数据挑战备受瞩目的复杂案件需要全面的取证解决方案;需要快速确定关键文档和证据的优先级;需要最新的支持来访问隐藏在多个来源和格式中的数据。结果为客户提供强大的取证调查解决方案;加速可辩护证据收集和分析;确保为最广泛的设备、格式和系统提供最新支持。故事DigitalDisc

2024字节跳动校招面试真题汇总及其解答(五)

17.TCP的拥塞控制TCP的拥塞控制是指在TCP连接中,发送端和接收端通过协作来控制网络中数据包的流量,避免网络拥塞。TCP的拥塞控制是TCP协议的重要组成部分,它可以确保TCP连接的稳定性和可靠性。TCP的拥塞控制主要有以下几个目的:防止网络拥塞:当网络中的数据包流量过大时,会导致网络拥塞,从而导致数据包丢失、延迟

共用体与枚举类型

9.7共用体9.7.1引例【例10.1】高校学生的课程设置中,有些课程是必修课,有些是选修课程,各门课程的考核方式不同,必修课采用百分制,选修课可以采用百分制和五级制(如'A'、'B'、'C'、'D'、'E')两种。学生在完成学校规定的课程的同时,可以根据需要选择自己感兴趣的一些课程。假设某个学期有三门选修课程:统计学

ESP32-IDF使用I2S驱动MAX98375--解析WAV文件

一.简介本篇文章将介绍如何使用ESP32S3通过I2S发送WAV音频数据,驱动MAX98375A进行音频的播放。是EVE_V2项目开发的一部分工作。二.MAX98375A介绍芯片特性如下,可以在芯片手册上找到。单电源工作(2.5V至5.5V)3.2W输出功率:4Ω,5V2.4mA静态电流92%效率(RL=8Ω,POUT

商家收款一万手续费多少

目前微信和支付宝作为主流的支付平台,为商家提供了安全、便捷的支付解决方案。但是在正常情况下,商家需要向平台支付交易额0.6%至1%不等的手续费,这个费率看似很少,但长期积累下来的手续费支出也是一笔不小的开支。什么是收款手续费率?收款手续费率是指的是我们商家在用收款码收款的时候,每次收款都会被微信或者支付宝扣一笔费用,这

Linux日志管理-logrotate(crontab定时任务、Ceph日志转储)

文章目录一、logrotate概述二、logrotate基本用法三、logrotate运行机制logrotate参数四、logrotate是怎么做到滚动日志时不影响程序正常的日志输出呢?Linux文件操作机制方案一方案二五、logrotate实战--Ceph日志转储参考一、logrotate概述logrotate是一个

盛元广通农业种子检测实验室信息化管理系统LIMS

农业问题以及粮食安全关系着我们的基本民生,尤其是随着农业科技的发展,借助现代化实验室管理系统,在种子质量检验中能让实验室检验实现自动化运行,实现无纸化和信息化办公,让数据分析得到科学完整的管理,减少运行成本。盛元广通农业种子检测实验室信息化管理系统LIMS结合工作实际流程制作,从种子采购、种子入库、种子库存、更新提醒、

智云谷再获AR HUD新项目定点,打开HUD出口海外新通道

深圳前海智云谷科技有限公司(以下简称“智云谷”)于近日收到国内某新能源车企的《定点通知书》,选择智云谷作为其新车型ARHUD开发与量产供应商。智云谷获得定点的车型为海外出口车型,该车型预计在2024年下半年量产。中国汽车全产业链出海“圈粉”随着中国新能源车的强势崛起,中国车企纷纷开始拓展海外市场。海关总署数据显示,今年

单点登录原理及JWT实现

单点登录原理及JWT实现一、单点登录效果首先我们看通过一个具体的案例来加深对单点登录的理解。案例地址:https://gitee.com/xuxueli0323/xxl-sso?_from=gitee_search把案例代码直接导入到IDEA中然后分别修改下server和samples中的配置信息在host文件中配置1

热文推荐