Creating a CacheManager

All usages of the Ehcache API start with the creation of a CacheManager. The following code snippets illustrate various ways to create one.

Singleton versus Instance

The following creates a singleton CacheManager using defaults, then list caches.

CacheManager.create();
String[] cacheNames = CacheManager.getInstance().getCacheNames();

The following creates a CacheManager instance using defaults, then list caches.

CacheManager manager = CacheManager.newInstance();
String[] cacheNames = manager.getCacheNames();

The following creates two CacheManagers, each with a different configuration, and list the caches in each.

CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
CacheManager manager2 = CacheManager.newInstance("src/config/ehcache2.xml");
String[] cacheNamesForManager1 = manager1.getCacheNames();
String[] cacheNamesForManager2 = manager2.getCacheNames();

Loading a Configuration

When a CacheManager is created, it creates caches found in a provided configuration.

The following creates a CacheManager based on the configuration defined in the ehcache.xml file in the classpath.

CacheManager manager = CacheManager.newInstance();

The following creates a CacheManager based on a specified configuration file.

CacheManager manager = CacheManager.newInstance("src/config/ehcache.xml");

The following creates a CacheManager from a configuration resource in the classpath.

URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = CacheManager.newInstance(url);

The following creates a CacheManager from a configuration in an InputStream.

InputStream fis = new FileInputStream(new File ("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = CacheManager.newInstance(fis);
} finally {
fis.close();
}

Adding and Removing Caches Programmatically

Adding Caches Programmatically

You are not limited to using caches that are placed in the CacheManager configuration. A new cache based on the default configuration can be added to a CacheManager very simply:

manager.addCache(cacheName);

For example, the following adds a cache called testCache to CacheManager called singletonManager. The cache is configured using defaultCache from the CacheManager configuration.

CacheManager singletonManager = CacheManager.create();
singletonManager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");

As shown below, you can also create a new cache with a specified configuration and add the cache to a CacheManager. Note that when you create a new cache, it is not usable until it has been added to a CacheManager.

CacheManager singletonManager = CacheManager.create();
Cache memoryOnlyCache = new Cache("testCache", 5000, false, false, 5, 2);
singletonManager.addCache(memoryOnlyCache);
Cache test = singletonManager.getCache("testCache");

Below is another way to create a new cache with a specified configuration. This example creates a cache called testCache and adds it CacheManager called manager.

// Create a singleton CacheManager using defaults
CacheManager manager = CacheManager.create();
// Create a Cache specifying its configuration.
Cache testCache = new Cache(new CacheConfiguration("testCache", maxEntriesLocalHeap)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
manager.addCache(testCache);

For a full list of parameters for a new Cache, see the Cache constructor at http://ehcache.org/xref/net/sf/ehcache/Cache.html.

Removing Caches Programmatically

The following removes the cache called sampleCache1:

CacheManager singletonManager = CacheManager.create();
singletonManager.removeCache("sampleCache1");

Performing Basic Cache Operations

The following examples refer to manager, which is a reference to a CacheManager that contains a cache called sampleCache1.

Obtaining a reference to a Cache

The following obtains a Cache called sampleCache1, which has been preconfigured in the configuration file

Cache cache = manager.getCache("sampleCache1");

Putting an Element in Cache

The following puts an element into a cache

Cache cache = manager.getCache("sampleCache1");
Element element = new Element("key1", "value1");
cache.put(element);

Updating and Element in Cache

The following updates an element in a cache. Even though cache.put( ) is used, Ehcache knows there is an existing element, and considers the put operation as an update for the purpose of notifying cache listeners.

Cache cache = manager.getCache("sampleCache1");
cache.put(new Element("key1", "value1"));
// This updates the entry for "key1"
cache.put(new Element("key1", "value2"));

Getting an Element from Cache

The following gets a Serializable value from an element with a key of key1.

Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Serializable value = element.getValue();

The following gets a NonSerializable value from an element with a key of key1.

Cache cache = manager.getCache("sampleCache1");
Element element = cache.get("key1");
Object value = element.getObjectValue();

Removing an Element from Cache

The following removes an element with a key of key1.

Cache cache = manager.getCache("sampleCache1");
cache.remove("key1");

Obtaining Cache Sizes

The following gets the number of elements currently in the cache.

Cache cache = manager.getCache("sampleCache1");
int elementsInMemory = cache.getSize();

The following gets the number of elements currently in the MemoryStore.

Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getMemoryStoreSize();

The following gets the number of elements currently in the DiskStore.

Cache cache = manager.getCache("sampleCache1");
long elementsInMemory = cache.getDiskStoreSize();

Shutdown the CacheManager

You should shut down a CacheManager after use. It does have a shut-down hook, but it is a best practice to shut it down in your code.

The following shuts down the singleton CacheManager:

CacheManager.getInstance().shutdown();

The following shuts down a CacheManager instance, assuming you have a reference to the CacheManager called manager:

manager.shutdown();

For additional examples, see CacheManagerTest at http://ehcache.org/xref-test/net/sf/ehcache/CacheManagerTest.html.

Ehcache(2.9.x) - API Developer Guide, Basic Caching的更多相关文章

  1. Ehcache(2.9.x) - API Developer Guide, Key Classes and Methods

    About the Key Classes Ehcache consists of a CacheManager, which manages logical data sets represente ...

  2. Ehcache(2.9.x) - API Developer Guide, Transaction Support

    About Transaction Support Transactions are supported in versions of Ehcache 2.0 and higher. The 2.3. ...

  3. Ehcache(2.9.x) - API Developer Guide, Write-Through and Write-Behind Caches

    About Write-Through and Write-Behind Caches Write-through caching is a caching pattern where writes ...

  4. Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms

    About Cache Eviction Algorithms A cache eviction algorithm is a way of deciding which element to evi ...

  5. Ehcache(2.9.x) - API Developer Guide, Cache Usage Patterns

    There are several common access patterns when using a cache. Ehcache supports the following patterns ...

  6. Ehcache(2.9.x) - API Developer Guide, Searching a Cache

    About Searching The Search API allows you to execute arbitrarily complex queries against caches. The ...

  7. Ehcache(2.9.x) - API Developer Guide, Using Explicit Locking

    About Explicit Locking Ehcache contains an implementation which provides for explicit locking, using ...

  8. Ehcache(2.9.x) - API Developer Guide, Blocking and Self Populating Caches

    About Blocking and Self-Populating Caches The net.sf.ehcache.constructs package contains some applie ...

  9. Ehcache(2.9.x) - API Developer Guide, Cache Loaders

    About Cache Loaders A CacheLoader is an interface that specifies load() and loadAll() methods with a ...

随机推荐

  1. C#中托管与非托管

    在.net 编程环境中,系统的资源分为托管资源和非托管资源. 对于托管的资源的回收工作,是不需要人工干预回收的,而且你也无法干预他们的回收,所能够做的 只是了解.net CLR如何做这些操作.也就是说 ...

  2. ElasticSearch中文分词(IK)

    ElasticSearch常用的很受欢迎的是IK,这里稍微介绍下安装过程及测试过程.   1.ElasticSearch官方分词 自带的中文分词器很弱,可以体检下: [zsz@VS-zsz ~]$ c ...

  3. 常用小方法 or 语法

    --> 获取外部文件 def groovyUtils = new GroovyUtils( context ) def xmlFilePath = groovyUtils.getProjectP ...

  4. 浅谈IT员工管理

    本人尽管还不是管理人员,但也管理过学弟们(不是同校.仅仅是工作中同事,为了好称呼叫学弟).也被管理着,工作也好多年了.今天又感而发.想来谈谈假设管理好员工(在此声明,我仅仅是发表个人意见哦.不要喷.哈 ...

  5. Codeforces Round #326 (Div. 2) C. Duff and Weight Lifting 水题

    C. Duff and Weight Lifting Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest ...

  6. 05.pathinfo的两种模式与模版和控制器之间的关系

    <?php function dump($data){ echo '<pre>'; var_dump($data); echo '</pre>'; } dump($_SE ...

  7. iOS开发——图形编程OC篇&粘性动画以及果冻效果

    粘性动画以及果冻效果 在最近做个一个自定义PageControl——KYAnimatedPageControl中,我实现了CALayer的形变动画以及CALayer的弹性动画,效果先过目: 先做个提纲 ...

  8. Activate、Deactivate 事件 Activate ThrottleEvent;

    http://help.adobe.com/zh_CN/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-8000.html   Activate.De ...

  9. mybatis0212 mybatis逆向工程 (MyBatis Generator)

    1mybatis逆向工程 (MyBatis Generator) .1什么是mybatis的逆向工程 mybatis官方为了提高开发效率,提高自动对单表生成sql,包括生成 :mapper.xml.m ...

  10. /proc/sys/net/ipv4/下各项的意义

        /proc/sys/net/ipv4/icmp_timeexceed_rate这个在traceroute时导致著名的“Solaris middle star”.这个文件控制发送ICMP Tim ...