2021-05-12 14:32:11
Spring Cache整合EHCache
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>
本文永久更新連結地址:http://www.linuxidc.com/Linux/2016-09/135125.htm
相關文章