常見(jiàn)的緩存技術(shù)
ehcache:hibernate底層
memcache:
redis:常用
-
jar包:
360截圖20190722191024047.jpg -
ehcache使用步驟:
1.導(dǎo)入jar包
2.編寫(xiě)配置文件
3.使用api
獲取數(shù)據(jù)先從緩存中獲取
若獲取的值為空
再去查詢數(shù)據(jù)庫(kù),
將數(shù)據(jù)放入緩存中public List<Category> findAll() throws Exception {
//1.創(chuàng)建緩存管理器CacheManager cm=CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml")); //2.獲取指定的緩存 Cache cache = cm.getCache("categoryCache"); //3.通過(guò)緩存獲取數(shù)據(jù) 將cache看成一個(gè)map即可 Element element = cache.get("clist"); List<Category> list=null; //4.判斷數(shù)據(jù) if(element==null){ //從數(shù)據(jù)庫(kù)中獲取 CategoryDao cd=(CategoryDao) BeanFactory.getBean("CategoryDao"); list=cd.findAll(); //將list放入緩存 cache.put(new Element("clist", list)); System.out.println("緩存中沒(méi)有數(shù)據(jù),已去數(shù)據(jù)庫(kù)中獲取"); }else{ //直接返回 list=(List<Category>) element.getObjectValue(); System.out.println("緩存中有數(shù)據(jù)"); } return list;}
xml配置文件內(nèi)容以及注釋如下:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="C:/ehcache"/>
<cache
name="categoryCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<!--
默認(rèn)緩存配置,
以下屬性是必須的:
name :cache的標(biāo)識(shí)符,在一個(gè)CacheManager中必須唯一。
maxElementsInMemory : 在內(nèi)存中緩存的element的最大數(shù)目。
maxElementsOnDisk : 在磁盤(pán)上緩存的element的最大數(shù)目。
eternal : 設(shè)定緩存的elements是否有有效期。如果為true,timeouts屬性被忽略。
overflowToDisk : 設(shè)定當(dāng)內(nèi)存緩存溢出的時(shí)候是否將過(guò)期的element緩存到磁盤(pán)上。
以下屬性是可選的:
timeToIdleSeconds : 緩存element在過(guò)期前的空閑時(shí)間。
timeToLiveSeconds : 緩存element的有效生命期。
diskPersistent : 在VM重啟的時(shí)候是否持久化磁盤(pán)緩存,默認(rèn)是false。
diskExpiryThreadIntervalSeconds : 磁盤(pán)緩存的清理線程運(yùn)行間隔,默認(rèn)是120秒.
memoryStoreEvictionPolicy : 當(dāng)內(nèi)存緩存達(dá)到最大,有新的element加入的時(shí)候,
移除緩存中element的策略。默認(rèn)是LRU,可選的有LFU和FIFO
-->
</ehcache>
