ehcache 使用筆記


要想使用 java 的本地緩存,可以考慮用 ehcache,或者 guava。

guava 更高端一點,可以自動定時刷新。我選擇了 ehcache。

在 spring 中是集成了 ehcache 的。要使用 ehcache 的話,只需要下面幾步:

當然需要首先引入 ehcache 相關的 jar 包。可以采用配置 pom 文件使用 maven 依賴的方式。

一、在 spring 的 applicationContext.xml 配置文件中配置好 ehcache 相關的 bean

    <!-- ehcache -->
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation" value="spring/ehcache.xml"/>  
    </bean>  
    <bean id="manager" class="org.springframework.cache.ehcache.EhCacheCacheManager">  
        <property name="cacheManager" ref="cacheManagerFactory"/>
    </bean>

 

二、配置好 ehcache.xml

<?xml version="1.0" encoding="gbk"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <diskStore path="java.io.tmpdir"/>
 
    <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false"/>
    <!-- 
        配置自定義緩存
        maxElementsInMemory:緩存中允許創建的最大對象數
        eternal:緩存中對象是否為永久的,如果是,超時設置將被忽略,對象從不過期。
        timeToIdleSeconds:緩存數據的鈍化時間,也就是在一個元素消亡之前,
                    兩次訪問時間的最大時間間隔值,這只能在元素不是永久駐留時有效,
                    如果該值是 0 就意味着元素可以停頓無窮長的時間。
        timeToLiveSeconds:緩存數據的生存時間,也就是一個元素從構建到消亡的最大時間間隔值,
                    這只能在元素不是永久駐留時有效,如果該值是0就意味着元素可以停頓無窮長的時間。
        overflowToDisk:內存不足時,是否啟用磁盤緩存。
        memoryStoreEvictionPolicy:緩存滿了之后的淘汰算法。
    -->
    <cache name="TerritoryCache" 
        maxElementsInMemory="10000" 
        eternal="false"
        overflowToDisk="false" 
        timeToIdleSeconds="900" 
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LFU" />
 
</ehcache>

 

三、具體類中使用 CacheManager

@Component
public class TerritoryRangeCache {
    @Autowired
    EhCacheCacheManager manager;

    @Autowired
    TerritoryRangeDao territoryRangeDao;

    Cache cache;

    public Object getAllTerritorRanges(String key) {

      cache = manager.getCacheManager().getCache("TerritoryCache");

        Object value = cache.get(key);
        if (value == null) {
            cache.putIfAbsent(new Element(key, territoryRangeDao.selectAll()));
            return cache.get(key).getObjectValue();
        }
        return cache.get(key).getObjectKey();
    }
}

其實具體類中使用注入的 EhCacheCacheManager 是 spring 自己封裝過了的 CacheManager。要想獲取引入的 ehCache 包里面的 CacheManager 的話,需要把spring 包裝過的EhCacheCacheManager通過 getManager 拿出來。我們來看先EhCacheCacheManager的源碼:

public class EhCacheCacheManager extends AbstractTransactionSupportingCacheManager {

    private net.sf.ehcache.CacheManager cacheManager;


    /**
     * Create a new EhCacheCacheManager, setting the target EhCache CacheManager
     * through the {@link #setCacheManager} bean property.
     */
    public EhCacheCacheManager() {
    }

    /**
     * Create a new EhCacheCacheManager for the given backing EhCache CacheManager.
     * @param cacheManager the backing EhCache {@link net.sf.ehcache.CacheManager}
     */
    public EhCacheCacheManager(net.sf.ehcache.CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }


    /**
     * Set the backing EhCache {@link net.sf.ehcache.CacheManager}.
     */
    public void setCacheManager(net.sf.ehcache.CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    /**
     * Return the backing EhCache {@link net.sf.ehcache.CacheManager}.
     */
    public net.sf.ehcache.CacheManager getCacheManager() {
        return this.cacheManager;
    }
……
}

四、ehcaceh 的定時刷新,可以自己寫一個方法,來更新緩存中的數據:

  @Scheduled(cron = " ")
    @PostConstruct
    public void refreshAll() {
        cache = manager.getCacheManager().getCache("key");
        getAllTerritorRanges("territory_range");
    }

可以加上上面的方法,來通過 cron 表達式中傳入的參數來定時刷新緩存中的數據。

關於@PostConstruct的使用以及含義,會在我的另一篇博文中介紹~。可以先看下這個注解的源碼:

package javax.annotation;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

/**
 * The PostConstruct annotation is used on a method that needs to be executed
 * after dependency injection is done to perform any initialization. This
 * method MUST be invoked before the class is put into service. This
 * annotation MUST be supported on all classes that support dependency
 * injection. The method annotated with PostConstruct MUST be invoked even
 * if the class does not request any resources to be injected. Only one
 * method can be annotated with this annotation. The method on which the
 * PostConstruct annotation is applied MUST fulfill all of the following
 * criteria -
- The method MUST NOT have any parameters except in the case of EJB
 * interceptors   in which case it takes an InvocationC ontext object as
 * defined by the EJB   specification.
 * - The return type of the method MUST be void.
 * - The method MUST NOT throw a checked exception.
 * - The method on which PostConstruct is applied MAY be public, protected,
 * package private or private.
 * - The method MUST NOT be static except for the application client.
 * - The method MAY be final.
 * - If the method throws an unchecked exception the class MUST NOT be put into
 * service except in the case of EJBs where the EJB can handle exceptions and
 * even   recover from them.
 * @since Common Annotations 1.0
 * @see javax.annotation.PreDestroy
 * @see javax.annotation.Resource
 */
@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

看注釋就能看懂吧~


免責聲明!

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



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