歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Spring Cache集成EHCache

Spring Cache集成EHCache

日期:2017/2/28 13:48:59   编辑:Linux教程

EHCache支持內存和磁盤的緩存,支持LRU、LFU和FIFO多種淘汰算法,支持分布式的Cache,可以作為Hibernate的緩存插件。同時它也能提供基於Filter的Cache,該Filter可以緩存響應的內容並采用Gzip壓縮提高響應速度。

可以通過spring集成提供緩存管理,spring為ehcache提供了如下的實現類:
EhCacheCache實現Cache接口
EhCacheCacheManager實現CacheManager接口
EhCache工廠管理類
EhCacheFactoryBean
EhCacheManagerFactoryBean
1.引入ehcache jar包


<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.6</version>
</dependency>
2.ehcache配置


<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect">
<!-- <diskStore path="java.io.tmpdir" /> -->
<diskStore path="C:/cache_tmpdir" />

<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
maxElementsOnDisk="10000000" diskPersistent="false"
diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />

<cache name="userCache" maxElementsInMemory="10000"
maxElementsOnDisk="1000" eternal="false" overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300" timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU" />

</ehcache>
3.spring配置


<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"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- 啟用緩存注解功能,這個是必須的,否則注解不會生效,另外,該注解一定要聲明在spring主配置文件中才會生效 -->
<cache:annotation-driven cache-manager="cacheManager" />

<bean id="userService" class="org.springframework.cache.demo.UserService" />

<!-- cacheManager工廠類,指定ehcache.xml的位置 -->
<bean id="cacheManagerFactory"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml" />

<!-- 聲明cacheManager -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="cacheManagerFactory" />
</beans>

Copyright © Linux教程網 All Rights Reserved