Ehcache 的簡單實用 及配置


Ehcache 與 spring 整合后的用法,下面是一個Ehcache.xml配置文件;

通用的緩存策略 可以用一個 cache;

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
 4          updateCheck="false">
 5 
 6     <!--
 7     diskStore:為緩存路徑,ehcache分為內存和磁盤 2級,此屬性定義磁盤的緩存位置
 8     user.home - 用戶主目錄
 9     user.dir - 用戶當前工作目錄
10     java.io.tmpdir - 默認臨時文件路徑
11     -->
12 <diskStore path="java.io.tmpdir/Tmp_Ehcache" />
13     <!--
14       name:緩存名稱。
15       maxElementsInMemory:緩存最大數目
16       maxElementsOnDisk:硬盤最大緩存個數。
17       eternal:對象是否永久有效,一但設置了,timeout將不起作用。
18       overflowToDisk:是否保存到磁盤,當系統當機時
19       timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。
20       timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
21       diskPersistent:是否緩存虛擬機重啟期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
22       diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。
23       diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
24       memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。
25        clearOnFlush:內存數量最大時是否清除。
26         memoryStoreEvictionPolicy:可選策略有:LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)。
27            FIFO,first in first out,這個是大家最熟的,先進先出。
28            LFU, Less Frequently Used,就是上面例子中使用的策略,直白一點就是講一直以來最少被使用的。如上面所講,緩存的元素有一個hit屬性,hit值最小的將會被清出緩存。
29            LRU,Least Recently Used,最近最少使用的,緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那么現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存。
30    -->
31 <defaultCache
32         eternal="false"
33         maxElementsInMemory="1000"
34         overflowToDisk="false"
35         diskPersistent="false"
36         timeToIdleSeconds="0"
37         timeToLiveSeconds="600"
38         memoryStoreEvictionPolicy="LRU"
39 />
40     <cache
41             name="demo"
42             eternal="false"
43             maxElementsInMemory="100"
44             overflowToDisk="false"
45             diskPersistent="false"
46             timeToIdleSeconds="0"
47             timeToLiveSeconds="300"
48             memoryStoreEvictionPolicy="LRU"
49     />
50 
51 </ehcache>
View Code

其實緩存無非就是減少數據庫的查詢操作,接下來簡單說下在 代碼中的使用方法,

先把ehcache 配置到 spring中(下面是使用spring-boot)

package com.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.persistence.Cache;

/**
 * Created by ding on 2017-04-25.
 */
@Configuration
@EnableCaching//標記啟動緩存
public class CacheConfiguration {
    //ehcache 主要的管理器 EhcacheManager

    @Bean
    public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){
        EhCacheManagerFactoryBean factoryBean=new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factoryBean.setShared(true);//也說是說通過這個來設置cache的基地是這里的Spring獨用,還是跟別的(如hibernate的Ehcache共享)
        return factoryBean;
    }

    @Bean
    public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean factoryBean){
        System.out.println("CacheConfiguration.ehcacheManager()");
        return new EhCacheCacheManager(factoryBean.getObject());

    }


}

 

留意下java代碼@cacheAble 注解中的 value 對應 ehcache.xml中定義的cache的name屬性(沒有找到,就會用默認的配置)

@cacheAble 注解中的 key 就是緩存的key,調用方法的時候,就是根據這個key是否存在緩存中 從而決定是否進入方法

注意:@cacheable注解只能用在實現類中,不能再接口中使用!!!

@Service
public class InfoServiceImpl {

   //value屬性表示使用哪個緩存策略,緩存策略在ehcache.xml中
    //LRU(最近最少使用,默認策略)、FIFO(先進先出)、LFU(最少訪問次數)
    public static final String DEMO_CACHE_NAME = "demo";//這個demo和ehcache中的 name對應

    //所有key 中的單引號 都不能少,不然會被識別成一個對象
    @Cacheable(value = DEMO_CACHE_NAME, key = "'info_'+#id")
    public String findNameById(Integer id) {
//Cacheable 不存在這個key 才會進入方法 System.out.println(
"沒有走緩存:" + id); return "zhangsan"; } @CacheEvict(value = DEMO_CACHE_NAME, key = "'info_'+#id")//清除緩存:是根據這個key來清理的,沒有找到key對應的緩存就沒清理了public void delete(Integer id) { //數據庫刪除操作……(略) } @CachePut(value = DEMO_CACHE_NAME, key = "'info_'+#infos.getId()") public String update(String str) { /*
@cachePut 表示重新放入緩存對象,不管是否存在這個key的緩存,所以一定會進入方法
*/ return str; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM