Spring框架中的Cache抽象层

为了统一支持各种各样的Cache,Spring框架从3.1开始,为应用提供了对各种Cache的一致抽象层。

说到Cache,这里首先需要指出的是,什么样的数据需要放入Cache呢?那就是应用中通过执行Java方法而得到的结果。


Spring框架的Cache抽象层围绕如下两个接口,封装了不同Cache的实现,为应用提供统一的调用接口:

  • org.springframework.cache.Cache接口
  • org.springframework.cache.CacheManager接口

Spring框架的Cache抽象层兼容如下第三方缓存实现:
  • 基于JDK的java.util.concurrent.ConcurrentMap的缓存
  • EhCache缓存
  • Guava缓存
  • Gemfire缓存
  • 兼容JSR-107的任何缓存

Spring框架提供了大量的缓存相关的标注,在应用中通过使用这些缓存标注就可以实现数据的缓存。要使用缓存标注,首先需要在Spring框架的XML配置文件中设置如下:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
        <cache:annotation-driven />
</beans>

然后,就可以在应用中引用如下Spring框架的缓存标注:
  • @Cacheable("a_cache_name"),作用于被缓冲的方法,对方法执行结果的缓存
  • @CacheEvict,作用于被缓冲的方法,将方法执行的结果从缓存中移除
  • @CachePut,更新缓存
  • @Caching,将作用于一个方法的多个缓存操作打包为一个整体
  • @CacheConfig,作用于Java类,设置通用的缓存相关参数

事实上,JSR-107 (JCache)标准已经定义了缓存的标准标注,标准标注与Spring框架的缓存标注的对应关系如下:
  • @CacheResult,类似于Spring的@Cacheable
  • @CachePut,类似于Spring的@CachePut
  • @CacheRemove,类似于Spring的@CacheEvict
  • @CacheRemoveAll,类似于Spring的@CacheEvict(allEntries=true)
  • @CacheDefaults,类似于Spring的@CacheConfig
  • @CacheKey
  • @CacheValue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值