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

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

公众号新闻

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入芋道快速开发平台知识星球。下面是星球提供的部分资料: 

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号等等功能:

  • Boot 地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro
  • Cloud 地址:https://gitee.com/zhijiantianya/yudao-cloud
  • 视频教程:https://doc.iocoder.cn

来源:blog.csdn.net/wodejiaAA/
article/details/132989681


Spring 提供了对缓存的支持,允许你将数据存储在缓存中以提高应用程序的性能。Spring 缓存抽象基于 Java Caching API,但提供了更简单的编程模型和更高级的功能。

Spring 集成缓存提供了一种方便的方式来使用缓存,从而提高应用程序的性能。Spring 缓存抽象提供了通用的缓存支持,并集成了常见的缓存解决方案。

缓存接口

Spring 的缓存 API 以注解方式提供。Spring缓存接口定义主要由org.springframework.cache.Cacheorg.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 Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 视频教程:https://doc.iocoder.cn/video/

开启注解

Spring 为缓存功能提供了注解功能,但是你必须启动注解:

(1) 在 xml 中声明

使用cache:annotation-driven/<cache:annotation-driven cache-manager=“cacheManager”/>

(2) 使用标记注解

通过对一个类进行注解修饰的方式在这个类中使用缓存注解。

范例如下:

@Configuration
@EnableCaching
public class AppConfig {
}

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud
  • 视频教程:https://doc.iocoder.cn/video/

缓存注解使用

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>

参考资料

https://docs.spring.io/


欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,长按”或“扫描”下方二维码噢

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

文章有帮助的话,在看,转发吧。

谢谢支持哟 (*^__^*)

微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
一泡一揉,血渍轻松搞定,还能抑菌除螨,不买对不起自己的内衣!上身瘦10斤,这件“软糯”针织连帽衫,79元轻松搞定秋冬穿搭![哇塞]电车智能化了, 这辅助功能看呆我?!大温一家四口跑长途出游靠TA轻松搞定【健康】还在应用程序上识别毒蘑菇?不准!多人中毒丢掉 LangChain、像 Docker一样编排大模型应用程序:这支十余人的年轻创业团队如何在2个月做出一个LLMOps平台?5137 血壮山河之武汉会战 信罗战役 10One Last Walk 最后一程 【小说】掌握十种诊断策略,轻松搞定家族性高胆固醇血症诊断如何在 Next.js 全栈应用程序中无缝实现身份验证入手这条吉普家百搭休闲卫裤,穿遍四季都不过时,79元到手!轻松搞定日常穿搭!《薇藤花》&《无字碑》小学体测成绩计入中考,别焦虑,这些神器能帮孩子轻松搞定体能练习!轻松搞定分布式 token 校验剑指 Kubernetes!微软发布开源平台 Radius:高效构建、运行云原生应用程序Grayjay:可能是终极的视频流应用程序 | Linux 中国手机APP也能救命!休斯顿司机使用应用程序救了另一名司机上身显瘦的“软糯”针织连帽衫,79元轻松搞定秋冬穿搭!【汉宫春】雨夜孤独 Han Palace Spring: Lonely Night in the Rain上身瘦10斤,这件「软糯」针织连帽衫,轻松搞定秋冬穿搭!免费领 | 火爆全网的清华附小英语动画全300集!轻松搞定小学全部知识点!Java近期新闻:Spring Framework 6.1、Spring Data 2023.1、Payara Platform没想到!这套书轻松掰透奥数,让孩子轻松搞定数学大题...第十章 美国社会的方方面面 (1)叫车应用程序Ryde Group冲刺纽交所:年营收658万美元像Docker一样编排大模型应用程序:这支十余人的年轻创业团队如何在2个月做出一个LLMOps平台?推荐35款 SpringBoot/SpringCloud 开源项目,附源码团|早秋款上新!经典百搭实穿,轻松搞定整套穿搭!Linux 上的最佳白板应用程序 | Linux 中国三明治这么做,好吃停不下来,轻松搞定娃早餐!人生困境与白左自辩上身显瘦的“软糯”针织连帽衫,轻松搞定秋冬穿搭!Spring Cache 缓存注解这样用,实在是太香了!胰岛素剂量总调不好?3 步轻松搞定!三口之家的全屋清洁助手-莱克洗地机轻松搞定,轻而强劲,一净到底如何正确教育青少年使用应用程序与科技?入秋后想要皮肤透亮,多喝这一碗!无油无糖轻松搞定!
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。