概述
CacheManager是SPI(Service Provider Interface,服务提供程序接口),提供了访问缓存名称和缓存对象的方法,同时也提供了管理缓存、操作缓存和移除缓存的方法。
下面我们来看下SpringCache框架说提供的不同的缓存管理器实现
SimpleCacheManager
通过使用SimpleCacheManager可以配置缓存列表,并利用这些缓存进行相关的操作。
SimpleCacheManager是缓存管理器的简化版本。 我们来看一下下面的配置实例。 对应缓存的定义,我们使用了ConcurrentMapCacheFactoryBean类对ComcurrentMapCache进行实例化,该实例使用了JDK的ConcurrentMap实现。
<!-- (1)添加cache命名空间和schema文件 --> <!-- (2)开启支持缓存的配置项 --> <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="true"/> <!-- (3) 配置cacheManger --> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager" p:caches-ref="cacheObjects"> </bean> <!-- (4)caches集合 --> <util:set id="cacheObjects"> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/> <!-- @Cacheable(cacheNames = "littleArtisan")标注的cache名称 --> <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="littleArtisan"/> </util:set>
NoOpCacheManager
NoOpCacheManager主要用于测试目的,事实上它并不缓存任何数据。 我们来看下该缓存管理器的配置定义,我们没有未该管理器提供缓存列表,因为它仅仅作为测试的目的
<bean id="noOpCacheManager" class="org.springframework.cache.support.NoOpCacheManager"/>
ConcurrentMapCacheManager
ConcurrentMapCacheManager使用了JDK的ConcurrentMap。 它提供了与SimpleCacheManager类似的共鞥,但并不需要像前面那样定义缓存。 该缓存定义如下:
<bean id="concurrentMapCacheManager" class="org.springframework.cache.concurrent.ConcurrentMapCacheManager"/>
CompositeCacheManager
CompositeCacheManager能够定义多个缓存管理器。
当在应用程序上下文中声明 <cache:annotation-driven>标记时,它只提供一个缓存管理器,有的时候并不能满足用户的需求,而CompositeCacheManager定义将多个缓存管理器定义组合在一起,从而扩展了该功能。
此外,CompositeCacheManager还提供了一种机制,通过使用fallbackToNoOpCache属性回到NoOpCacheManager.
我们来看下面的的例子: 定义了一个CompositeCacheManager,将一个简单的缓存管理器与HazelCast缓存管理器绑定到一起 。 简单的缓存管理器定义了members缓存,而HazelCast缓存管理器定义了visitors.
<bean id="compositeCacheManager" class="org.springframework.cache.support.CompositeCacheManager"> <property name="cacheManagers"> <list> <!-- SimpleCacheManager --> <bean class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean id="membes" class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"></bean> </set> </property> </bean> <!-- HazelcastCacheManager --> <bean id="cacheManager" class="com.hazelcast.spring.cache.HazelcastCacheManager"> <constructor-arg ref="hazelcast" /> </bean> </list> </property> </bean> <hz:hazelcast id="hazelcast"> <hz:config> <hz:map name="vistors"> <hz:map-store enabled="true" class-name="com.sartisan.cache.domain.Vistor" write-delay-seconds="0" /> </hz:map> </hz:config> </hz:hazelcast>