Playframework之cache

Cache實現緩存

Play容器啓動時(play.Play.start()),調用play.cache.Cache.init()mvc

檢查application.conf配置文件中,是否開啓了memcachedapp

           a) 未開啓memcached則開啓一個ehcache實例memcached

           b) 若開啓memcached但鏈接memcached失敗,則會啓動一個ehcacheurl

Cache使用memcached配置線程

配置一個memcachedrest

memcached=disabled (開啓 enabled,關閉disabled)xml

memcached.host= 127.0.0.1:11211對象

memcached.user=username內存

memcached.password=password

配置多個memcached

memcached=disabled (開啓 enabled,關閉disabled)

memcached.1.host= 127.0.0.1:11211

memcached.2.host= 127.0.0.1:11211

play中Ehcache的配置

配置文件playframework/src/ehcache.xml

 

maxElementsInMemory="10000"             //內存中最大緩存對象數

eternal="false"                         //Element是否永久有效,一但設置了,timeout將不起做用

timeToIdleSeconds="120"                 //設置Element在失效前的容許閒置時間。僅當element不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。

timeToLiveSeconds="120"                 //設置Element在失效前容許存活時間。最大時間介於建立時間和失效時間之間。僅當element不是永久有效時使用,默認是0.,也就是element存活時間無窮大。

overflowToDisk="false"                  // 當緩存中元素的數量超過限制時,就把這些元素持久化到硬盤,若是overflowToDisk是false ,那麼maxElementsOnDisk 的設置就沒有什麼意義了

maxElementsOnDisk="10000000"            //持久化該緩存的元素到硬盤上的最大數量

diskPersistent="false"                  //Whether the disk store persists between restarts of the Virtual Machine.

diskExpiryThreadIntervalSeconds="120 "  //磁盤失效線程運行時間間隔,默認是120秒

memoryStoreEvictionPolicy="LRU"         //當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你能夠設置爲FIFO(先進先出)或是LFU(較少使用)

 

自定義ehcache配置

在app目錄下面,新建ehcache配置的xml文件ehcache.xml

     

自定緩存實現Cache

自定義一個playPlugin

重寫 play.PlayPlugin.onLoad()

在onLoad方法中,設置Cache屬性 play.cache.Cache.forcedCacheImpl

     參見源碼: play.cache.Cache.init()和play.Play.start()

 

Play自帶的controller緩存

play自帶了controller緩存,play.cache.CacheFor 在controller方法上加上註解後,play將會爲方法提供緩存(源碼:play.mvc.ActionInvoker.invoke(Request, Response))

// Check the cache (only for GET or HEAD)

if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {

    cacheKey = actionMethod.getAnnotation(CacheFor.class).id();

    if ("".equals(cacheKey)) {

        cacheKey = "urlcache:" + request.url + request.querystring;

    }

    actionResult = (Result) play.cache.Cache.get(cacheKey);

}

相關文章
相關標籤/搜索