今天就跟大家聊聊有關Ehcache緩存框架如何在Java項目中使用 ,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
前言
JAVA緩存實現方案有很多,最基本的自己使用Map去構建緩存,或者使用memcached或Redis,但是上述兩種緩存框架都要搭建服務器,而Map自行構建的緩存可能沒有很高的使用效率,那么我們可以嘗試一下使用Ehcache緩存框架。
Ehcache主要基于內存緩存,磁盤緩存為輔的,使用起來方便。下面介紹如何在項目中使用Ehcache
入門使用教程
1.maven引用
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.4</version> </dependency>
2.在classpath下建立一個ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!--timeToIdleSeconds 當緩存閑置n秒后銷毀 --> <!--timeToLiveSeconds 當緩存存活n秒后銷毀 --> <!-- 緩存配置 name:緩存名稱。 maxElementsInMemory:緩存最大個數。 eternal:對象是否永久有效,一但設置了,timeout將不起作用。 timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。 timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介于創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。 overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。 diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。 maxElementsOnDisk:硬盤最大緩存個數。 diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。 memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。 clearOnFlush:內存數量最大時是否清除。 --> <!-- 磁盤緩存位置 --> <diskStore path="java.io.tmpdir/easylink-mall-web/ehcache"/> <!-- 默認緩存 --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <!-- 商戶申請數據緩存 數據緩存40分鐘 --> <cache name="merchant-apply-cache" eternal="false" timeToIdleSeconds="2400" timeToLiveSeconds="2400" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"> </cache> </ehcache>
3.與spring的cacheManager結合使用
<?xml version="1.0" encoding="UTF-8"?> <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" 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"> <!-- 支持緩存注解 --> <cache:annotation-driven cache-manager="cacheManager" /> <!-- 默認是cacheManager --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="cacheManagerFactory"/> </bean> <!-- cache管理器配置 --> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"/> <property name="shared" value="true" /> </bean> </beans>
4.代碼使用
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.easylink.mall.entity.Merchant;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class EhcacheTest {
@Autowired
private CacheManager cacheManager;
@Test
public void execute() {
// 獲取商戶申請緩存容器
Cache cache = cacheManager.getCache("merchant-apply-cache");
Merchant merchant = new Merchant();
Long id = IdWorker.getId();
merchant.setId(id);
merchant.setName("緩存測試");
// 將商戶申請數據添加至緩存中 // key : id value : object
cache.put(id, merchant);
// 獲取商戶申請數據
// 方法1
Merchant cacheMerchant1 = (Merchant) cache.get(id).get();
System.out.println(cacheMerchant1.getName());
// 方法2
Merchant cacheMerchant2 = cache.get(id, Merchant.class);
System.out.println(cacheMerchant2.getName());
// 將商戶申請數據從緩存中移除
cache.evict(id);
}
}5.注意事項
cache.get(key) 和cache.get(key, class);方法,由于不知道你存入的key是什么類型,所以get的時候不會做key的類型檢查,如上述例子中
Long id = IdWorker.getId(); cache.put(id, merchant); Merchant cacheMerchant2 = cache.get(id, Merchant.class);
put進去時的key是Long類型的,get的時候也只能傳入對應Long類型的key才能獲取到對應的value,如果傳入的是String類型的key,即使兩個key的值是一致的,也會導致無法獲取到對應的value。這個情況很容易發生在對request請求的參數,由于是String字符串類型,但是忘了做類型轉換就直接把這個String當做key去獲取對應的value。導致獲取不到,請同學們要注意,親身經歷,血與淚的教訓。
看完上述內容,你們對Ehcache緩存框架如何在Java項目中使用 有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。