Spring对缓存的支持

本文章差不多来自于Spring的官方文档
原文档的英文链接为
https://docs.spring.io/spring/docs/4.3.3.RELEASE/spring-framework-reference/htmlsingle/#cache

Spring3.1引入了缓存,和事务一样,它拥有极少的侵入性。
在4.1中被加入Jsr107,支持定制

关于缓存和buffer的了解
Obviously this approach works only for methods that are guaranteed to return the same output (result) for a given input (or arguments) no matter how many times it is being executed.

最后这种抽象被Cache和CacheManger接口具体化。
实现基于ConcurrentHashMap
Ehcache 2.x
Gemfire cache
Caffeine
Guava caches
JSR-107 compliant caches (e.g. Ehcache 3.x)

缓存 没有对多线程特殊处理

基于注解的缓存
这些注解位于context的annoation包下
@Cacheable
也差不多
@CacheEivct
可以设置在方法类接口上 可以设置的属性也挺多的。
@CachePut
和上一个差不多
@Caching
可以设置put evict等
@CacheConfig
可以设置cacheNames keyGenerator cacheManger cacheResolver等属性。

然后是几个抽象类

concurrent包
interceptor包
configer包
suport包

有两个重要接口Cache 和CacheManger接口

基于xml的缓存

<!-- the service we want to make cacheable -->
<bean id="bookService" class="x.y.service.DefaultBookService"/>

<!-- cache definitions -->
<cache:advice id="cacheAdvice" cache-manager="cacheManager">
    <cache:caching cache="books">
        <cache:cacheable method="findBook" key="#isbn"/>
        <cache:cache-evict method="loadBooks" all-entries="true"/>
    </cache:caching>
</cache:advice>

<!-- apply the cacheable behavior to all BookService interfaces -->
<aop:config>
    <aop:advisor advice-ref="cacheAdvice" pointcut="execution(* x.y.BookService.*(..))"/>
</aop:config>

<!-- cache manager definition omitted -->



常见几种缓存的用法
enhance

<bean id="cacheManager"
      class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cache-manager-ref="ehcache"/>

<!-- EhCache library setup -->
<bean id="ehcache"
      class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml"/>

写的乱的很

如果在SpringBoot没有定义一个CacheManger类型的Bean,或者一个cacheResolver(cacheconfig)
SpringBoot对缓存的尝试供应商支持顺序

Genric
Jcache(ehcache3)
ehcache2
hazelcast
infinispan
couchbase
redis
caffeine
guaua
simple

也可以强制指定属性
spring.cache.type指定缓存供应商
CacheMangerCustomizer 自定义配置

如果有一个定义好的cache bean 一个cachemanger包装着它,那么采用通用缓存。

如果在classpath下找到ehcache.xml则缓存使用ehcache2.x

hazelcast也需要指定配置文件
需要显示指定infinispan配置文件

CoucheBase配置

Redis可用并且配置好,将会被自动配置
可以使用spring.cache.cache-names改为启动时创建其他缓存

Caffeine
java8对guaua的重写 SpringBoot2.0取代guaua,如果出现caffeine自动化配置

Guaua

Simple
如果上面选项都没有被实现,将会配置一个使用ConcurrentHashMap作为缓存存储的简单实例被配置,这是缓存没有添加第三方lib的默认配置。

关于缓存的强制禁用spring.cache.type=none。针对某些特定的环境。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值