Java緩衝Ehcache-核心類和方法介紹及使用執行個體,javaehcache-
Ehcache中核心類和方法
EhCache裡面有一個CacheManager類型,它負責管理cache。Cache裡面儲存著Element對象,Element必須是key-value對。Cache是實際物理實現的,在記憶體中或者磁碟。這些組件的邏輯表示就是下面即將要討論的類。他們的方法提供了可程式化的訪問方式。
CacheManager
負責Cache的建立、訪問、移除。
CacheManager建立
CacheManager支援兩種建立模式:單例(Singleton mode)和執行個體(InstanceMode)。
在2.5之前的版本中,在同一個JVM中允許存在任意數量相同名字的CacheManager。每調用new CacheManager(...)一次,就會產生一個新的CacheManager執行個體,而不管已經存在多少個。調用CacheManager.create(...),則返回的是已經存在的那個配置對應的單例CacheManager,如果不存在,則建立一個。
2.5之後的版本,不允許在同一個JVM記憶體在多個具有相同名字的CacheManager。建立非單例執行個體的CacheManager()建構函式可能會打破這一規則,但是會拋出NPE異常。如果你的代碼要在同一個JVM建立多個同名的執行個體,請使用靜態方法CacheManager.create(),總是返回對應名的CacheManager(如果已經存在),否則建立一個。
事實上,我們可以直接利用Spring中的EhCacheManagerFactoryBean[spring2.5.4]來幫我們完成CacheManager的建立,看看它的具體建立方式:
if (this.shared) {// Shared CacheManager singleton at the VM level.if (this.configLocation != null) {this.cacheManager = CacheManager.create(this.configLocation.getInputStream());}else {this.cacheManager = CacheManager.create();}}else {// Independent CacheManager instance (the default).if (this.configLocation != null) {this.cacheManager = new CacheManager(this.configLocation.getInputStream());}else {this.cacheManager = new CacheManager();}}if (this.cacheManagerName != null) {this.cacheManager.setName(this.cacheManagerName);}
EhCache2.5.2及其以上版本的建立方法歸納如下:
- CacheManager.newInstance(Configuration configuration) :建立一個新的CacheManager 對象或者返回已經存在的對應配置中名字的CacheManager
- CacheManager.create():建立一個新的預設配置的單例CacheManager ,或者返回一個已經存在的單例。
- CacheManager.create(Configuration configuration),建立一個對應傳入設定檔中名字的單例CacheManager,或者返回已經存在的單例CacheManager。
- new CacheManager(Configuration configuration),建立一個新的CacheManager,或者如果對應配置的CacheManager已經存在或配置參數為空白,拋出異常。
在Instance Mode中,如果Cache均使用MemoryStore,則沒有什麼特別需要注意的。但是如果使用了DIskStore,那麼每個CacheManager必須具有不同的diskStore路徑。當一個新的CacheManager被建立的時候,需要檢查沒有別的CacheManager使用同樣的DiskStore路徑。如果有,就會拋出異常CacheException。如果CacheManager是叢集中一部分,那麼其監聽連接埠必須唯一。
Singletonmode和Instance Mode可以混合使用,而不會產生衝突。
Ehcache
所有的cache都實現了介面Ehcache。每個cache都有名字和屬性,且包含Element。
Ehcache中的cache相當於其他緩衝系統中的一塊快取區域。
Element
Element是存放於cache中的原子單位。它有一個key、一個value以及關於訪問的記錄。Element被放進到cache或者從cache移除。他們也可能會由於到期被移除,這依賴於配置。
使用執行個體
下面給出了一個使用Ehcache的實際例子。
首先建立一個maven java工程,在pom.xml中添加Ehcache依賴。
<!-- Ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version> </dependency>
下面是java代碼。代碼實現的功能非常簡單,即建立CacheManager,往裡面存放一個Cache,然後往cache裡面存資料和取資料,目的是展示Ehcache的基本使用。
/** * XXX.com Inc. * Copyright (c) 2004-2014 All Rights Reserved. */package com.test.encache;import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;import net.sf.ehcache.Element;/** * * @author XXX * @version $Id: EncacheTest.java, v 0.1 2014年8月8日 下午5:30:03 XXX Exp $ */public class EncacheTest { //一些配置參數 //private final static String configFileName = "ehcache.xml"; //private final static int maxEntriesLocalHeap = 1000; private static CacheManager cacheManager; static String cacheName = "cache1"; public static void main(String[] args) { ehcacheSetUp(); ehcacheUse(); } private static void ehcacheSetUp() { cacheManager = CacheManager.create(); //CacheConfiguration configuration = new CacheConfiguration(configFileName, // maxEntriesLocalHeap); //Cache cache = new Cache(configuration); cacheManager.addCache(cacheName); } private static void ehcacheUse() { Cache cache1 = cacheManager.getCache(cacheName); String key = "key1"; String value = "value1"; writeSomeData(cache1, key, value); Element element = readSomeData(cache1, key, value); System.out.println(element); } private static void writeSomeData(Cache cache, String key, String value) { cache.put(new Element(key, value)); } private static Element readSomeData(Cache cache, String key, String value) { return cache.get(key); }}
程式輸出:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1411807398768, LastAccessTime = 1411807398771 ]
其中的錯誤資訊是因為沒有配置日誌相關的SLF4J所致。
下面我們要配置日誌。首先在pom.xml中添加依賴:
<!-- SLF4J --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version></dependency>
然後建立log4j的設定檔log4j.properties:
# Root logger optionlog4j.rootLogger=INFO, file, stdoutlog4j.logger.com.test.encache.EncacheTest=INFO,file # Direct log messages to a log filelog4j.appender.file=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.file.File=C:\\logging.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Direct log messages to stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
並且將這個檔案放置到工程的classpath下,在這裡我建立的是用Eclipse建立的maven工程,將其放置在工程主目錄下的\target\classes檔案夾下。
然後在代碼中添加logger的初始化代碼:
private static final Logger logger = LoggerFactory.getLogger(EncacheTest.class);
然後就可以使用了:
logger.info("Setup ehcache");
輸出:
2014-09-27 17:22:45 INFO EncacheTest:35 - Setup ehcache2014-09-27 17:22:45 WARN ConfigurationFactory:136 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/MavenRepo/net/sf/ehcache/ehcache/2.8.3/ehcache-2.8.3.jar!/ehcache-failsafe.xml2014-09-27 17:22:46 WARN DiskStorePathManager:162 - diskStorePath 'C:\Users\xiajun.xj\AppData\Local\Temp' is already used by an existing CacheManager either in the same VM or in a different process.The diskStore path for this CacheManager will be set to C:\Users\xiajun.xj\AppData\Local\Temp\ehcache_auto_created7989392067865891865diskstore.To avoid this warning consider using the CacheManager factory methods to create a singleton CacheManager or specifying a separate ehcache configuration (ehcache.xml) for each CacheManager instance.[ key = key1, value=value1, version=1, hitCount=1, CreationTime = 1411809766273, LastAccessTime = 1411809766276 ]
參考資料:
來源文件 <http://ehcache.org/documentation/get-started/key-classes-methods>
ehcache緩衝可以在jdbc中使用?配置案例及步驟
sdfsdf
Java的應用緩衝cache怎入門?
跟session不是一個概念,簡單的談下我個人對緩衝的看法吧,你可以把它想象成一個容量大的hashMap,可以往裡面get set資料,由於資料存在記憶體當中而不是資料庫中,所以存取速度較快。
java常用的緩衝有:ehcache, oscache,jcache,這些cache都是單機的,即存在原生記憶體中,另外分布式的cache我用過memcache,它被獨立部署在一台伺服器上,可以實現多個用戶端共用緩衝。
一般用到緩衝的情境:1.在處理並發請求,需要及時響應的。2.加快系統響應速度。舉個例子:比如購物網站有 售賣物品的熱門排行榜,這種資料都是由資料庫中N多表關聯查詢排序得到的,那麼就可以存在緩衝當中,當頁面請求查看熱門排行榜時直接取緩衝中的資料。後台定時任務根據一定的時間間隔計算好排行結果,再替換到當前緩衝中。 這就是一個簡單的緩衝應用樣本。
具體用法你可以參考 各個緩衝的說明文檔,百度一下很多的。 純手打,望採納~