本文章差不多来自于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。针对某些特定的环境。