Oscache使用詳解,配置,使用,細節

  1. 1、OSCache是什麼?   

  2.   OSCache標記庫由OpenSymphony設計,它是一種開創性的緩存方案,它提供了在現有JSP頁面之內實現內存緩存的功能。OSCache是個一個被廣泛採用的高性能的J2EE緩存框架,OSCache還能應用於任何Java應用程序的普通的緩存解決方案。

  3. 2、OSCache的特點 

  4.  (1) 緩存任何對象:你可以不受限制的緩存部分jsp頁面或HTTP請求,任何java對象都可以緩存。  

  5.  (2) 擁有全面的API:OSCache API允許你通過編程的方式來控制所有的OSCache特性。

  6.  (3) 永久緩存:緩存能被配置寫入硬盤,因此允許在應用服務器的多次生命週期間緩存創建開銷昂貴的數據。 

  7.  (4) 支持集羣:集羣緩存數據能被單個的進行參數配置,不需要修改代碼。 

  8.  (5) 緩存過期:你可以有最大限度的控制緩存對象的過期,包括可插入式的刷新策略(如果默認性能不能滿足需要時)。

  9. 3、OSCache緩存的三種模式

  10.  (1)緩存於內存中

  11.  (2)緩存於硬盤中

  12.  (3)一種較靈活的方式,先緩存於內存中,如果滿了則轉至硬盤

  13. 4、OSCache的安裝與配置   

  14. OSCache是當前運用最廣的緩存方案,JBoss,Hibernate,Spring等都對其有支持

  15.  

  16. 下面簡單介紹一下OSCache的配置和使用過程。

  17. 1.安裝過程

  18. 從http://www.opensymphony.com/oscache/download.html下載合適的OSCache版本

  19. 解壓壓縮文件得到文件夾oscache-2.4.1-full

  20.  

  21. 從解壓縮目錄取得oscache.jar 文件放到/WEB-INF/lib 或相應類庫目錄中,jar文件名可能含有版本號和該版本的發佈日期信息等,如oscache-2.4.1.jar

  22. 將lib下的commons-logging.jar和jgroups-all.jar都放入到/WEB-INF/lib中

  23. 拷貝OSCache標籤庫文件oscache.tld到src目錄或者/WEB-INF/classes目錄。

  24. 從src或etc目錄取得oscache.properties 文件,放入src根目錄或發佈環境的/WEB-INF/classes 目錄

  25.  

  26. 如你需要建立磁盤緩存,須修改oscache.properties 中的cache.path信息 (去掉前面的#註釋)。

  27.  

  28. 內容如下:

  29. Cache.manory=false;

  30. cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashPersistenceListener;

  31. win類路徑類似爲c:\\app\\cache

  32. unix類路徑類似爲/opt/myapp/cache

  33.  

  34.  

  35. 現在你的應用目錄類似如下:

  36. $WEB_APPLICATION\WEB-INF\lib\oscache.jar

  37. $WEB_APPLICATION\WEB-INF\lib\commons-logging.jar

  38. $WEB_APPLICATION\WEB-INF\lib\jgroups-all.jar

  39. $WEB_APPLICATION\WEB-INF\classes\oscache.properties

  40. $WEB_APPLICATION\WEB-INF\classes\oscache.tld

  41.  

  42. 將下列代碼加入web.xml文件中即可使用OSCache提供的標籤了

  43.  <jsp-config>

  44.   <taglib>

  45.     <taglib-uri>oscache</taglib-uri>

  46.     <taglib-location>/WEB-INF/classes/oscache.tld</taglib-location>

  47.   </taglib>

  48.  </jsp-config>

  49. 2.oscache.properties 文件配置嚮導(源文件已經寫好了只要將語句前面的#號去掉即可)

  50.  

  51. cache.memory值爲true 或 false ,默認爲在內存中作緩存,如設置爲false,即將緩存的數據存到cache.path配置好的路徑下

  52.  

  53. cache.capacity:緩存元素個數

  54.  

  55. cache.persistence.class   持久化緩存類,如此類打開,則必須設置cache.path信息

  56.  

  57. cache.cluster 相關

  58. 爲集羣設置信息。

  59. cache.cluster.multicast.ip爲廣播IP地址

  60. cache.cluster.properties爲集羣屬性

  61.  

  62. 5.OSCache的基本用法

  63. 1.OSCache標籤的使用

  64. 注意:要使用標籤必須在web.xml中配置好之後再在頁面中引入,在頁面開始加入<%@ taglib uri="oscache"prefix="cache" %>句即可

  65. 以下兩個頁面是使用OSCache標籤的例子:

  66.  

  67. index1.jsp 內容如下

  68. <%@page import="java.util.*" %>

  69. <%@taglib uri="oscache" prefix="cache" %>

  70. <html>

  71. <body>

  72. <!—未使用到標籤-->

  73. 沒有緩存的日期: <%= new Date() %>

  74.  

  75. <!--自動刷新但是沒有給標記符key賦值-->

  76. <cache:cache time="30">

  77.   每30秒刷新緩存一次的日期:<%= new Date() %>

  78. </cache:cache>

  79.  

  80. <!--手動刷新,給標記符key賦值了-->

  81. <cache:cache key="testcache">

  82.   手動刷新緩存的日期: <%= new Date() %> <p>

  83. </cache:cache>

  84. <ahref="index2.jsp">手動刷新</a>

  85. </body>

  86. </html>

  87. index2.jsp 執行手動刷新頁面如下:

  88. <%@taglib uri="oscache" prefix="cache" %>

  89. <html>

  90. <body>

  91.  

  92. 緩存已刷新...<p>

  93. <!—根據key定位到index1.jsp頁面的testcache,範圍爲application,使用的是flush標籤用來清空緩存-->

  94. <cache:flush key="testcache" scope="application"/>

  95. <a href="index1.jsp">返回</a>

  96. </body>

  97. </html>

  98.  

  99. 你也可以通過下面語句定義Cache的有效範圍,如不定義scope,scope默認爲Applcation

  100. <cache:cache time="30"scope="session">

  101.   內容...

  102. </cache:cache>

  103.  

  104. 6. 緩存過濾器 CacheFilter

  105. 如果是對頁面進行緩存則需要在web.xml中定義緩存過濾器,定義特定資源的緩存。

  106. <filter>

  107.   <filter-name>CacheFilter</filter-name>

  108.   <filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>

  109.   <init-param>

  110.     <param-name>time</param-name>

  111.     <param-value>60</param-value>

  112.   </init-param>

  113.   <init-param>

  114.     <param-name>scope</param-name>

  115.     <param-value>session</param-value>

  116.   </init-param>

  117. </filter>

  118.  

  119. <filter-mapping>

  120.   <filter-name>CacheFilter</filter-name>

  121.   <url-pattern>*.jsp</url-pattern>

  122. </filter-mapping>

  123.  

  124. 上面定義將緩存所有.jsp頁面,緩存刷新時間爲60秒,緩存作用域爲Session

  125.  

  126. 注意:如果要加入其它的屬性的話只要添加一個<init-param>標籤對,在其中添加相應的屬性,用法跟在jsp頁面使用標籤是一致的

  127.  

  128. 注意,CacheFilter只捕獲Http頭爲200的頁面請求,即只對無錯誤請求作緩存,而不對其他請求(如500,404,400)作緩存處理

  129.  

  130. 7、主要的標籤以及標籤屬性

  131. Cache標籤——緩存代碼段主要使用到的標籤:

  132. 屬性說明:

  133. key
     標識緩存內容的關鍵詞。在指定的作用範圍內必須是唯一的。默認的key是被訪問頁面的URI和後面的請求字符串。可以在同一個頁面中使用很多cache 標籤而不指定他的key屬性,這種情況下系統使用該頁面的URI和後面的請求字符串,另外再自動給這些key增加一個索引值來區分這些緩存內容。但是不推 薦採用這樣的方式。

    scope
     緩存發生作用的範圍,可以是application或者session。默認爲application。

    time
     緩存內容的時間段,單位是秒,默認是3600秒,也就是一個小時,如果設定一個負值,那麼這部分被緩存的內容將永遠不過期。

    duration
     指定緩存內容失效的時間,是相對time的另一個選擇,可以使用簡單日期格式或者符合USO-8601的日期格式。如:duration='PT5M' duration='5s'等。

  134.  

  135. 注意:time與duration的區別是time的單位是秒所以設置的時候是隻要輸入一個阿拉伯數字,而duration的話可以使用簡單日期格式或者符合USO-8601的日期格式。如:duration='PT5M' duration='5s'等


  136. cron
        指定緩存內容失效表達式。
        通過Cron表達式我們可以很靈活的設置緩存的失效時間,Cron表達式包括5個字段分別爲Minute,Hour, DOM(Day Of Month), Month,DOW(Day Of Week)。他們順序地對應了5個位置。當某個位置上的值爲*時,表示該位置上的任意時間。另外還提供了指定時間的操作符號"-",",","/",他們 分別表示一段時間範圍,具體的時間,以及遞增的時間段。下面是幾個例子說明一下Cron表達式的基本應用:
            (1) "10/20 * * * *" :因是第一個位置,並且是一個遞增的表達式,所以表達式指定的是每個小時的第10分鐘,第30分鐘,第50分鐘緩存內容失效。
            (2) "* 8-18/4 * * *" :指定每天早上8點到晚上6點之間,每4個小時緩存內容失效。  等同於"*8,12,16 * * *"。
            (3) "* * * * 1-5":表示每個星期一到星期五內容失效。

    refresh
     false 或者true。如果refresh屬性設置爲true,不管其他的屬性是否符合條件,這部分被緩存的內容都將被更新,這給編程者一種選擇,決定什麼時候必須刷新。

    mode
     如果不希望被緩存的內容增加到給用戶的響應中,可以設置mode屬性爲"silent"。此時被緩存的部分不在頁面上顯示,而其它任意的mode屬性值都會將緩存的部分顯示到頁面上。

    groups
     指定當前cache標籤所屬的組,可使用“,”分割組名。這樣就可以對緩存項進行分組了。如果緩存項依賴於應用的其它部分或其它數據,分組就有了用武之地——當這種依賴改變時(刷新相關的組),這個組的所有緩存項都將過期。

    language
     使用ISO-639定義的語言碼來發布不同的緩存內容(under an otherwise identical key)。要在一個多語言網站上同一段JSP代碼不同用戶的參數提供不同的語言時,這個屬性會很有用。

    refreshpolicyclass

  137. 指定自定義的刷新策略類的全限定類名。這個類繼承自

  138. com.opensymphony.oscache.web.WebEntryRefreshPolicy

    refreshpolicyparam
     指定任意需要傳給refreshpolicyclass的參數。如果沒有指定refreshpolicyclass,則這個值不起作用。

  139.  

  140. usecached標籤
            <usecached />:必須嵌套在<cache>標籤中。
    屬性說明:

    use
     告訴所在的<cache>標籤是否使用已經緩存的內容(缺省爲true,使用緩存的內容)。可以使用這個標籤來控制緩存。比如使用<frush>標籤刷新某個key的緩存,但可以在必要的地方即使這樣的強制刷新也仍然使用緩存內容而不刷新。

  141.  


  142. flush標籤
            這個標籤用於在運行時刷新緩存。只有運行flush標籤後再次訪問相關緩存項時才執行刷新。
    屬性說明:

    scope[all]
     指定要刷新的範圍。可選的值是"application","session" 和 nul。null(到底是null量還是all呀)值指定刷新所有的緩存(是指使用cache標籤的緩存)。

    key
     當指定了scope和key值時,刷新唯一的緩存項。當這個緩存項下次被訪問時將被刷新。只指定一個key值而沒有指定scope不起作用。

    group
     指定一個組時將刷新所有這個組中的緩存項。只指定一個group值而沒有指定scope不起作用。

    pattern
     任意包含pattern屬性指定的值的緩存項都將被刷新。只指定一個pattern值而沒有指定scope不起作用。 (注意:OSCache項目組已經不贊成使用pattern這個屬性賴刷新緩存,二是鼓勵使用具有更好的靈活性和性能的group屬性來代替)

    language
     使用ISO-639定義的語言碼來發布不同的緩存內容(under an otherwise identical key)。要在一個多語言網站上同一段JSP代碼不同用戶的參數提供不同的語言時,這個屬性會很有用。

  143. addgroup標籤
            <addgroup />:必須嵌套在<cache>標籤中。
    屬性說明: 

    group
    定義cache標籤的group名稱

  144. 示例代碼如下:
    <oscache:cache key="test1">
        <oscache:addgroupgroup="group1" />
            ... some jsp content ...
        <oscache:addgroupgroup="group2" />
        ... some more jsp content ...
    </oscache:cache>

  145. #一、內存緩存或硬盤、數據庫緩存  

  146. cache.memory=false  

  147.   

  148. #二、緩存的最大數量。默認是不限制,cache不會移走任何緩存內容。負數被視不限制。  

  149. cache.capacity=100  

  150.   

  151. #三、運算規則。爲了使用規則,cache的size必須是指定的。  

  152. #如果cache的size不指定的話, 將不會限制緩存對象的大小。如果指定了cache的size,但不指定algorithm,那它會默認使用:com.opensymphony.oscache.base.algorithm.LRUCache  

  153. #有下面三種規則:  

  154. #*com.opensymphony.oscache.base.algorithm.LRUCache:   

  155. #last in first out(最後插入的最先調用)。默認選項。  

  156. #*com.opensymphony.oscache.base.algorithm.FIFOCache:  

  157. #first int first out(最先插入的最先調用)。  

  158. #*com.opensymphony.oscache.base.algorithm.UnlimitedCache :   

  159. #cache中的內容將永遠不會被丟棄。  

  160. #如果cache.capacity不指定值的話,它將被設爲默認選項。  

  161. cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache  

  162.   

  163. #四、是否同步。true 或者 false。一般設爲true,避免讀取髒數據。  

  164. cache.blocking=true  

  165.   

  166. #五、指定硬盤緩存是否要作限制。默認值爲falsefalse的狀況下,disk cache capacity 和cache.capacity的值相同。  

  167. cache.unlimited.disk=false  

  168.   

  169. #六、指定類是被持久化緩存的類。class必須實現PersistenceListener接口。  

  170. #作爲硬盤持久,可以實現com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener接口。  

  171. #它把class的toString()輸出的hash值作爲文件的名稱。如果你要想文件名易讀些(自己設定),DiskPersistenceListener 的父類也能使用,但其可能有非法字符或者過長的名字。  

  172. #注意:HashDiskPersistenceListener 和 DiskPersistenceListener 需要設定硬盤路徑:cache.path  

  173. #cache.persistence.class=  

  174.   

  175. #七、指定硬盤緩存的路徑。目錄如果不存在將被建立。同時注意oscache應該要有權限寫文件系統。  

  176. #例: cache.path=c:\\myapp\\cache  cache.path=/opt/myapp/cache  

  177. cache.path=e:\\index\\cache  

  178.   

  179. #八、指定是否只有在內存不足的情況下才使用硬盤緩存。  

  180. #默認值false。但推薦是true如果內存cache被允許的話。這個屬性徹底的改變了cache的行爲,使得persisted cache和memory是完全不同。  

  181. cache.persistence.overflow.only=false  

  182.   

  183. #九、class名列表(用逗號隔開)。每個class必須實現以下接口中的一個 或者幾個  

  184. #CacheEntryEventListener:接收cache add/update/flush and remove事件  

  185. #CacheMapAccessEventListener :接收cache訪問事件。這個可以讓你跟蹤cache怎麼工作。  

  186. #默認是不配置任何class的。當然你可以使用一下的class:  

  187. #*com.opensymphony.oscache.plugins.clustersupport.BroadcastingCacheEventListener : 分佈式的監聽器。可以廣播到局域網內的其他cache實例。  

  188. #* com.opensymphony.oscache.extra.CacheEntryEventListenerImpl :一個簡單的監聽器。在cache的生命週期中記錄所有entry的事件。  

  189. #* com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl : 記錄count of cache map events(cache hits,misses and state hits).  

  190. #cache.event.listeners  

  191.   

  192. #十、在application 和 session的作用域時 用於標識cache 對象的,  用於ServletCacheAdministrator;此屬性不是指定爲"__oscache_cache"格式時爲默認值, 如果代碼中需要用到默認值時可以通使用com.opensymphony.oscache.base.Const.DEFAULT_CACHE_KEY 來取得;  

  193. cache.key=__oscache_cache  

  194.   

  195. #十一、當配置多個服務器時,想通過服備器名稱自動生成cache key時,可將此屬性設爲true. 默認值爲false;  

  196. cache.use.host.domain.in.key=true  

  197.   

  198. #十二、    在以上基礎選項之上可以加入一些額外的屬性到此文件中.例:  JavaGroupsBroadcastingListener 便是額外的  

  199. #Additional Properties  

  200.   

  201. #十三、用於緩存集羣. 默認爲231.12.21.132  

  202. #cache.cluster.multicast.ip  

  203.   

  204. #十四、    指集羣中的額外配置項. 以下是默認設置:(此屬性的相關說將在集羣文檔中說明)  

  205. #UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;\  

  206. #mcast_send_buf_size=150000;mcast_recv_buf_size=80000):\  

  207. #PING(timeout=2000;num_initial_members=3):\  

  208. #MERGE2(min_interval=5000;max_interval=10000):\  

  209. #FD_SOCK:VERIFY_SUSPECT(timeout=1500):\  

  210. #pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):\  

  211. #UNICAST(timeout=300,600,1200,2400):\  

  212. #pbcast.STABLE(desired_avg_gossip=20000):\  

  213. #FRAG(frag_size=8096;down_thread=false;up_thread=false):\  

  214. #pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)  

  215. #cache.cluster.properties  

  216.   

  217.   

  218. # CACHE IN MEMORY  

  219. #  

  220. # If you want to disable memory caching, just uncomment this line.  

  221. #  

  222. # cache.memory=false  

  223.   

  224.   

  225. # CACHE KEY  

  226. #  

  227. # This is the key that will be used to store the cache in the application  

  228. # and session scope.  

  229. #  

  230. # If you want to set the cache key to anything other than the default  

  231. # uncomment this line and change the cache.key  

  232. #  

  233. # cache.key=__oscache_cache  

  234.   

  235.   

  236. # USE HOST DOMAIN NAME IN KEY  

  237. #  

  238. # Servers for multiple host domains may wish to add host name info to  

  239. # the generation of the key.  If this is true, then uncomment the  

  240. # following line.  

  241. #  

  242. # cache.use.host.domain.in.key=true  

  243.   

  244.   

  245. # CACHE LISTENERS  

  246. #  

  247. # These hook OSCache events and perform various actions such as logging  

  248. # cache hits and misses, or broadcasting to other cache instances across a cluster.  

  249. # See the documentation for further information.  

  250. #  

  251. # cache.event.listeners=com.opensymphony.oscache.plugins.clustersupport.JMSBroadcastingListener,  \  

  252. #                       com.opensymphony.oscache.extra.CacheEntryEventListenerImpl,               \  

  253. #                       com.opensymphony.oscache.extra.CacheMapAccessEventListenerImpl,           \  

  254. #                       com.opensymphony.oscache.extra.ScopeEventListenerImpl,                    \  

  255. #                       com.opensymphony.oscache.extra.StatisticListenerImpl  

  256.   

  257.   

  258. # CACHE PERSISTENCE CLASS  

  259. #  

  260. # Specify the class to use for persistence. If you use the supplied DiskPersistenceListener,  

  261. # don't forget to supply the cache.path property to specify the location of the cache  

  262. # directory.  

  263. #   

  264. # If a persistence class is not specified, OSCache will use memory caching only.  

  265. #  

  266. # cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener  

  267. # cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener  

  268.   

  269. # CACHE OVERFLOW PERSISTENCE  

  270. # Use persistent cache in overflow or not. The default value is false, which means  

  271. # the persistent cache will be used at all times for every entry.  true is the recommended setting.  

  272. #  

  273. # cache.persistence.overflow.only=true  

  274.   

  275. # CACHE DIRECTORY  

  276. #  

  277. # This is the directory on disk where caches will be stored by the DiskPersistenceListener.  

  278. # it will be created if it doesn't already exist. Remember that OSCache must have  

  279. # write permission to this directory.  

  280. #  

  281. # Note: for Windows machines, this needs \ to be escaped  

  282. # ie Windows:  

  283. # cache.path=c:\\myapp\\cache  

  284. # or *ix:  

  285. # cache.path=/opt/myapp/cache  

  286. #  

  287. # cache.path=c:\\app\\cache  

  288.   

  289.   

  290. # CACHE ALGORITHM  

  291. #  

  292. # Default cache algorithm to use. Note that in order to use an algorithm  

  293. # the cache size must also be specified. If the cache size is not specified,  

  294. # the cache algorithm will be Unlimited cache.  

  295. #  

  296. # cache.algorithm=com.opensymphony.oscache.base.algorithm.LRUCache  

  297. # cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache  

  298. # cache.algorithm=com.opensymphony.oscache.base.algorithm.UnlimitedCache  

  299.   

  300. # THREAD BLOCKING BEHAVIOR  

  301. #  

  302. # When a request is made for a stale cache entry, it is possible that another thread is already  

  303. # in the process of rebuilding that entry. This setting specifies how OSCache handles the  

  304. # subsequent 'non-building' threads. The default behaviour (cache.blocking=false) is to serve  

  305. # the old content to subsequent threads until the cache entry has been updated. This provides  

  306. # the best performance (at the cost of serving slightly stale data). When blocking is enabled,  

  307. # threads will instead block until the new cache entry is ready to be served. Once the new entry  

  308. # is put in the cache the blocked threads will be restarted and given the new entry.  

  309. # Note that even if blocking is disabled, when there is no stale data available to be served  

  310. # threads will block until the data is added to the cache by the thread that is responsible  

  311. for building the data.  

  312. #  

  313. # cache.blocking=false  

  314.   

  315. # CACHE SIZE  

  316. #  

  317. # Default cache size in number of items. If a size is specified but not  

  318. # an algorithm, the cache algorithm used will be LRUCache.  

  319. #  

  320. #cache.capacity=1000  

  321.   

  322.   

  323. # CACHE UNLIMITED DISK  

  324. # Use unlimited disk cache or not. The default value is false, which means  

  325. # the disk cache will be limited in size to the value specified by cache.capacity.  

  326. #  

  327. # cache.unlimited.disk=false  

  328.   

  329.   

  330. # JMS CLUSTER PROPERTIES  

  331. #  

  332. # Configuration properties for JMS clustering. See the clustering documentation  

  333. for more information on these settings.  

  334. #  

  335. #cache.cluster.jms.topic.factory=java:comp/env/jms/TopicConnectionFactory  

  336. #cache.cluster.jms.topic.name=java:comp/env/jms/OSCacheTopic  

  337. #cache.cluster.jms.node.name=node1  

  338.   

  339.   

  340. # JAVAGROUPS CLUSTER PROPERTIES  

  341. #  

  342. # Configuration properites for the JavaGroups clustering. Only one of these  

  343. # should be specified. Default values (as shown below) will be used if niether  

  344. # property is set. See the clustering documentation and the JavaGroups project  

  345. # (www.javagroups.com) for more information on these settings.  

  346. #  

  347. #cache.cluster.properties=UDP(mcast_addr=231.12.21.132;mcast_port=45566;ip_ttl=32;\  

  348. #mcast_send_buf_size=150000;mcast_recv_buf_size=80000):\  

  349. #PING(timeout=2000;num_initial_members=3):\  

  350. #MERGE2(min_interval=5000;max_interval=10000):\  

  351. #FD_SOCK:VERIFY_SUSPECT(timeout=1500):\  

  352. #pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800;max_xmit_size=8192):\  

  353. #UNICAST(timeout=300,600,1200,2400):\  

  354. #pbcast.STABLE(desired_avg_gossip=20000):\  

  355. #FRAG(frag_size=8096;down_thread=false;up_thread=false):\  

  356. #pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;print_local_addr=true)  

  357. #cache.cluster.multicast.ip=231.12.21.132  

同一個應用可以實例化多個oscache的admin,使用不同的配置策略,如不同的配置文件。例如: 

Java代碼  收藏代碼

  1. Public class ChatRecordCache {  

  2.     private static GeneralCacheAdministrator admin;  

  3.     private static String OSCACHE_DISK =  "oscache_disk.properties";  

  4.     static {  

  5.         Properties prop = new Properties();   

  6.         try {  

  7.             prop.load(new FileInputStream(OSCACHE_DISK));  

  8.         } catch (FileNotFoundException e) {  

  9. //          e.printStackTrace();  

  10.         } catch (IOException e) {  

  11. //          e.printStackTrace();  

  12.         }  

  13.         admin = new GeneralCacheAdministrator(prop);  

  14.     }  

  15. }  

對應的配置文件爲oscache_disk.properties: 

Java代碼  收藏代碼

  1. cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener  

  2. cache.path=/opt/myapp/cache  

  3. cache.algorithm=com.opensymphony.oscache.base.algorithm.FIFOCache  

  4. cache.capacity=1000  

  5. cache.unlimited.disk=true  



Java代碼  收藏代碼

  1. public class ChatUserCache {  

  2.     private static GeneralCacheAdministrator admin = new GeneralCacheAdministrator();  

  3. }  

此處採用默認的配置文件oscache.properties. 

注意:如果多個cache實例產生的硬盤緩存路徑和緩存名稱完全相同,將會無法區分,此時要注意設置不同的key值區分。 

關於NeedsRefreshException,引用官方文檔中的一段例子如下: 

Java代碼  收藏代碼

  1. // ---------------------------------------------------------------  

  2. // Typical use with fail over  

  3. // 採取補救措施的典型方案  

  4. // ---------------------------------------------------------------  

  5.  String myKey = "myKey";  

  6.  String myValue;  

  7.  int myRefreshPeriod = 1000;  

  8.  try {  

  9.      // Get from the cache  

  10.      myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);  

  11.  } catch (NeedsRefreshException nre) {  

  12.     //This exception is thrown when retrieving an item from cache and it //is expired. Note that for fault tolerance purposes, it is possible //to retrieve the current cached object from the exception.  

  13.      try {  

  14.          // Get the value (probably by calling an EJB)  

  15.          myValue = "This is the content retrieved.";  

  16.          // Store in the cache  

  17.          admin.putInCache(myKey, myValue);//有解鎖的作用  

  18.      } catch (Exception ex) {//獲取myValue過程發生異常,無法執行到putInCache方法  

  19.          // We have the current content if we want fail-over.  

  20.          //採取補救措施,獲取可能的值(適用於數據過期的情況)  

  21.     myValue = (String) nre.getCacheContent();  

  22.       

  23.          // It is essential that cancelUpdate is called if the  

  24.          // cached content is not rebuilt  

  25.          admin.cancelUpdate(myKey);//解鎖  

  26.      }  

  27.  }  

這段代碼是使用oscache的經典代碼,細說如下。myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);從對象緩存map中取出myKey對應的對象,兩種情況可能發生: 一:如果myKey對應的對象存在(先前putInCache)並且沒有過期(isStale()方法)那麼getFromCache方法會正常返回。二:如果對應的對象不存在或者過期,分爲兩種情況:1)請求的線程第一個探測到對象不存在或者過期,那麼這個時候oscache會拋出一個NeedRefreshException, 提示需要對數據進行一下刷新,怎麼刷新,putInCache或者cancelUpdate即可。2)如果請求的線程並非第一個探測到對象不存在,兩種情況:A.之前探測到的線程沒有進行刷新處理,直接阻塞。B. 之前探測到的線程進行了刷新處理,拋出NeedRefreshException。3)如果請求的線程並非第一個探測到對象過期,兩種情況:A.之前探測到的線程沒有進行刷新處理,直接阻塞。B. 之前探測到的線程進行了刷新處理,又分兩種情況:I.如果oscache.properties中對blocking設置爲false(默認cache.blocking=false), 拋出NeedRefreshException,此處採取補救措施nre.getCacheContent(),會取出現有(很可能過期)內容。 II. 如果cache.blocking=true那麼該線程會在此阻塞,直到putInCache在另一個線程中被調用或者是cancelUpdate被調用。參考以下說明: 
cache.blocking 
When a request is made for a stale cache entry, it is possible that another thread is already in the process of rebuilding that entry. This setting specifies how OSCache handles the subsequent 'non-building' threads. The default behaviour (cache.blocking=false) is to serve the old content to subsequent threads until the cache entry has been updated. This provides the best performance (at the cost of serving slightly stale data). When blocking is enabled, threads will instead block until the new cache entry is ready to be served. Once the new entry is put in the cache the blocked threads will be restarted and given the new entry. 
Note that even if blocking is disabled, when there is no stale data available to be served threads will block until the data is added to the cache by the thread that is responsible for building the data. 

補充:oscache對一個cacheEntry是否是Stale(或者說expire)的判斷原則: 
1.Cache.flushEntry() 
2.Cache.flushAll() 
3.CacheEntry.setGroups(groups); Cache.flushGroup(group) 
4.createTime + refreshPeriod< now 
5.cronExpiry< now 
6.CacheEntry自帶的EntryRefreshPolish的needRefresh方法返回true 
上面的6條中的任何一條如果爲true, 那麼CacheEntry就是stale的,need refresh! 
官方文檔中的另一段例子如下: 

Java代碼  收藏代碼

  1. // ---------------------------------------------------------------  

  2. // Typical use without fail over  

  3. //不採取補救措施的典型方案  

  4. // ---------------------------------------------------------------  

  5.  String myKey = "myKey";  

  6.  String myValue;  

  7.  int myRefreshPeriod = 1000;  

  8.  try {  

  9.      // Get from the cache  

  10.      myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);  

  11.  } catch (NeedsRefreshException nre) {  

  12.      try {  

  13.          // Get the value (probably by calling an EJB)  

  14.          myValue = "This is the content retrieved.";  

  15.          // Store in the cache  

  16.          admin.putInCache(myKey, myValue);  

  17.          updated = true;  

  18.      } finally {  

  19.          if (!updated) {  

  20.              // It is essential that cancelUpdate is called if the  

  21.              // cached content could not be rebuilt  

  22.              admin.cancelUpdate(myKey);  

  23.          }  

  24.      }  

  25.  }  

  26.  // ---------------------------------------------------------------  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章