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

这篇具有很好参考价值的文章主要介绍了轻松搞定Spring集成缓存,让你的应用程序飞起来!。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

轻松搞定Spring集成缓存,让你的应用程序飞起来!,# Spring,spring,缓存,java文章来源地址https://www.toymoban.com/news/detail-723632.html

主页传送门:📀 传送

  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 官方文档

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

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

到了这里,关于轻松搞定Spring集成缓存,让你的应用程序飞起来!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 6种打包Python代码的方法,让你的程序变成exe应用

    Python是一种高级编程语言,它具有易学易用、跨平台等优点,因此在开发中得到了广泛的应用。 然而,Python代码需要在Python解释器中运行,这对于一些用户来说可能不太方便。 因此,将Python代码打包成可执行文件(exe)是一种很好的解决方案。 本文将介绍6种将Python代码打包

    2024年01月18日
    浏览(18)
  • 6种打包Python代码的方法,让你的程序变成exe应用!

    Python是一种高级编程语言,它具有易学易用、跨平台等优点,因此在开发中得到了广泛的应用。 然而,Python代码需要在Python解释器中运行,这对于一些用户来说可能不太方便。 因此,将Python代码打包成可执行文件(exe)是一种很好的解决方案。 本文将介绍6种将Python代码打包

    2024年02月16日
    浏览(14)
  • Vue实现二维码,让你的数据轻松传递

    在我们生活中,二维码的应用越来越广泛,特别是在移动互联网的时代,二维码成为了快速传达信息的一种利器。在这篇文章中,我们将会介绍如何在Vue框架下,实现一个具备扫描和查看数据的二维码。 在这一篇文章中,我们将会使用到以下两个库: qrcode.js :一个简单易用

    2024年02月05日
    浏览(18)
  • Python在生物信息学中的应用:让你的程序运行得更快

    程序运行太慢,想要提速,但不使用复杂的技术如 C 扩展或 JIT 编译器。 解决方案 程序优化的 第一准则是“不要优化” , 第二准则是“不要优化那些不重要的部分” 。基于这两个原则,如果你的程序运行得很慢,你得先找出影响性能的问题所在。 多数时候我们发现程序把

    2024年02月20日
    浏览(20)
  • 30个前端和设计必备网站,让你的工作更轻松!

    当今互联网时代,前端开发和设计领域变化迅速,每天都会有新技术和工具不断涌现。无论你是一名前端工程师还是一名设计师,都需要不断了解最新的前沿技术和工具。下面是30个前端和设计经常会用到的网站,以及每个网站的功能介绍。 链接:https://www.w3schools.com/ W3Scho

    2024年01月16日
    浏览(16)
  • 在飞书上轻松集成ChatGPT,3步搞定!

    为了让用户更便捷地使用 ChatGPT,我们将 ChatGPT 集成到飞书,设置只需要几分钟。 步骤一:获取飞书 Webhook URL 在应用商店或点击飞书官网下载飞书。下载安装后进入飞书界面,点击上方 ➕号 创建一个群组。 输入群名称,例如: ChatGPT , 并点击 创建 按钮。在新建的群组界面

    2024年02月07日
    浏览(25)
  • 分享 7 个有用的 Flutter 库,让你的开发生活更轻松

    让你的 Flutter 开发更高效 为什么要编写自定义功能,当你可以使用库呢?库是开发者最好的朋友和救命稻草。在我看来,一个好的项目应该充分利用一些最好的可用库。 本文是有关 Flutter 中很棒的库系列文章的一部分,我总结了7个 Flutter 库,这些库将有助于您在开发过程中

    2024年02月17日
    浏览(19)
  • 极速Python编程:利用缓存加速你的应用程序

    在软件开发中,缓存是一种常用的技术,用于提高系统性能和响应速度。Python提供了多种缓存技术和库,使我们能够轻松地实现缓存功能。本文将带您从入门到精通,逐步介绍Python中的缓存使用方法,并提供实例演示。 缓存基础知识 什么是缓存 缓存的工作原理 缓存的优势和

    2024年02月16日
    浏览(21)
  • 多丽特膳:个性化的调减饮品,让你的蜕变之路更轻松

    不同的人有不同的体型和健康状态,在我们的生活中存在九种体质,它们分别是平和质、气虚质、阳虚质、阴虚质、痰湿质、湿热质、血瘀质、气郁质、特禀质。体质是指人类个体在形态结构和生理功能方面的相对稳定的特征,它反映了人类个体之间的差异。这些体质的不同

    2024年02月05日
    浏览(15)
  • 9 个实用的 VSCode 扩展插件,让你的开发工作更轻松

    这些扩展将帮助您提高工作效率、改进工作流程 VSCode 是几乎所有编程语言中最受欢迎的 IDE 之一。它简单、强大,有很多很酷的特性,而且是微软的产品。所以对于任何开发人员来说,它都是一个很棒的工具。 通过安装其市场上可用的各种免费扩展,可以自定义 VS Code 并使

    2023年04月20日
    浏览(16)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包