ehcache是一個Java進程內緩存框架,有以下特色:java
快速簡單,容易集成spring
支持多種緩存策略緩存
緩存數據有兩級:內存和磁盤, 無需擔憂容量問題mvc
緩存數據會在虛擬機重啓的過程寫入磁盤框架
<?xml version="1.0" encoding="UTF-8"?> <ehcache updateCheck="false" name="txswx-ehcache"> <diskStore path="java.io.tmpdir"/> <!-- DefaultCache setting. --> <defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" maxEntriesLocalDisk="100000"/> <cache name="levelOneCache" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="1000" overflowToDisk="false" /> </ehcache>
name:緩存名稱shiroCache
eternal:對象是否永久有效,一旦設置true,timeout將不起做用
timeToIdleSeconds:設置對象在失效前的容許閒置時間
timeToLiveSeconds:設置對象在失效前的容許存活時間
overflowToDisk: 當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中
diskPersistent:是否緩存虛擬機重啓期數據
diskExpiryThreadIntervalSeconds: 磁盤失效線程運行時間間隔,默認是120秒
1. ehcache.xml分佈式
<ehcache updateCheck="false" name="shiroCache"> <!-- name:緩存名稱shiroCache eternal:對象是否永久有效,一旦設置true,timeout將不起做用 timeToIdleSeconds:設置對象在失效前的容許閒置時間 timeToLiveSeconds:設置對象在失效前的容許存活時間 overflowToDisk: 當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中 diskPersistent:是否緩存虛擬機重啓期數據 diskExpiryThreadIntervalSeconds: 磁盤失效線程運行時間間隔,默認是120秒 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> </ehcache>
2. mvc-dispatcher-servlet.xml配置測試
<!-- Cache配置 --> <cache:annotation-driven cache-manager="cacheManager"/> <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml"/> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehCacheManagerFactory"/>
3.測試類spa
public class EhcacheTest { private static final Logger LOG = LoggerFactory.getLogger(EhcacheTest.class); public static void main(String[] args) { Resource res = new ClassPathResource("mvc-dispatcher-servlet.xml"); BeanFactory factory = new XmlBeanFactory(res); CacheManager cacheManager = (CacheManager) factory.getBean("cacheManager"); Cache cache = cacheManager.getCache("levelOneCache"); User user = null; for (int i = 0; i < 10; i++) { Element element = cache.get("key"); if (element == null) { user = new User("test"); element = new Element("key", user); cache.put(element); LOG.info("cache object " + " can not retrieved from cache"); }else { user = (User)element.getValue(); LOG.info("cache object " + " can retrieve from cache"); } } } }
Ehcache在不少項目中都會被使用過, 用法比較簡單,通常加些配置就能夠了, Ehcache能夠對頁面 對象 數據進行緩存,Ehcache支持內存和磁盤的緩存, 支持分佈式的cache線程