ehcache 是优秀的基于硬盘策略的缓存技术。其优点 详见百度。。。这里 只是说明 ehcahe的简单使用已经基于spring-cache 的集成。
首先需要ehcache的配置文件:
<ehcache updateCheck="false">
<diskStore path="./ehcache"/>
<defaultCache
maxElementsInMemory="500"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="60"
timeToLiveSeconds="0"
diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<cache name="HttpClient"
maxElementsInMemory="300"
maxElementsOnDisk="0"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="60"
timeToLiveSeconds="0"
diskSpoolBufferSizeMB="50"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
</ehcache>
通过CacheManager 生成实例初始化 后 调用相关API 如:getCache(),cache.get(key)获取相关的缓存集合或者缓存集合中的缓存元素element。
spring-cache 有默认的缓存机制 如下配置即可:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
</bean>
如果需要集成ehcache 则只需要设置cacheManager 属性cacheManager
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager">
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-spring.xml"/>
</bean>
</property>
</bean>
当然要想缓存真正生效还需要添加注解(注意xmlschema中需要声明cache的定义路径)
<cache:annotation-driven/>
通过相关设置 只需要使用@Cacheable 等spring提供的接口即可使用相关缓存,其他注解请百度查询