About Cache Decorators

Ehcache uses the Ehcache interface, of which Cache is an implementation. It is possible and encouraged to create Ehcache decorators that are backed by a Cache instance, implement Ehcache and provide extra functionality.

The Decorator pattern is one of the well known Gang of Four patterns.

Decorated caches are accessed from the CacheManager using CacheManager.getEhcache(String name). Note that, for backward compatibility,CacheManager.getCache(String name) has been retained. However only CacheManager.getEhcache(String name) returns the decorated cache.

Built-in Decorators

BlockingCache

This is a Blocking decorator for Ehcache that allows concurrent read access to elements already in the cache. If the element is null, other reads will block until an element with the same key is put into the cache. This decorator is useful for constructing read-through or self-populating caches. BlockingCache is used by CachingFilter.

SelfPopulatingCache

A self-populating decorator for Ehcache that creates entries on demand. Clients of the cache simply call it without needing knowledge of whether the entry exists in the cache. If null, the entry is created. The cache is designed to be refreshed. Refreshes operate on the backing cache, and do not degrade performance of get calls.

SelfPopulatingCache extends BlockingCache. Multiple threads attempting to access a null element will block until the first thread completes. If refresh is being called the threads do not block - they return the stale data. This is very useful for engineering highly scalable systems.

Caches with Exception Handling

Caches with exception handlers are decorated. For information about adding an exception handler to a cache, see Cache Exception Handlers.

Creating a Decorator

Declarative Creation

You can configure decorators directly in ehcache.xml. The decorators will be created and added to the CacheManager.

It accepts the name of a concrete class that extends net.sf.ehcache.constructs.CacheDecoratorFactory

The properties will be parsed according to the delimiter (default is comma ",") and passed to the concrete factory's createDecoratedEhcache(Ehcache cache, Properties properties) method along with the reference to the owning cache.

It is configured as per the following example:

<cacheDecoratorFactory
class="com.company.SomethingCacheDecoratorFactory"
properties="property1=36 ..." />

Note that decorators can be configured against the defaultCache. This is very useful for frameworks like Hibernate that add caches based on the configuration of the defaultCache.

Programmatic Creation

Cache decorators are created as follows:

BlockingCache newBlockingCache = new BlockingCache(cache);

The class must implement Ehcache.

Adding Decorated Caches to a CacheManager

Having created a decorator programmatically, it is generally useful to put it in a place where multiple threads can access it. Note that decorators created via configuration in ehcache.xml have already been added to the CacheManager.

Using CacheManager.replaceCacheWithDecoratedCache()

A built-in way is to replace the Cache in CacheManager with the decorated one. This is achieved as in the following example:

cacheManager.replaceCacheWithDecoratedCache(cache, newBlockingCache);

The CacheManager.replaceCacheWithDecoratedCache() method requires that the decorated cache be built from the underlying cache from the same name.

Note that any overridden Ehcache methods will take on new behaviors without casting, as per the normal rules of Java. Casting is only required for new methods that the decorator introduces.

Any calls to get the cache out of the CacheManager now return the decorated one.

A word of caution. This method should be called in an appropriately synchronized init style method before multiple threads attempt to use it. All threads must be referencing the same decorated cache. An example of a suitable init method is found in CachingFilter:

/**
* The cache holding the web pages. Ensure that all threads for a given cache
* name are using the same instance of this.
*/
private BlockingCache blockingCache;
/**
* Initialises blockingCache to use
*
* @throws CacheException The most likely cause is that a cache has not been
* configured in Ehcache's configuration file ehcache.xml
* for the filter name
*/
public void doInit() throws CacheException {
synchronized (this.getClass()) {
if (blockingCache == null) {
final String cacheName = getCacheName();
Ehcache cache = getCacheManager().getEhcache(cacheName);
if (!(cache instanceof BlockingCache)) {
//decorate and substitute
BlockingCache newBlockingCache = new BlockingCache(cache);
getCacheManager().replaceCacheWithDecoratedCache(cache, newBlockingCache);
}
blockingCache = (BlockingCache) getCacheManager().getEhcache(getCacheName());
}
}
}
Ehcache blockingCache = singletonManager.getEhcache("sampleCache1");

The returned cache will exhibit the decorations.

Using CacheManager.addDecoratedCache()

Sometimes you want to add a decorated cache but retain access to the underlying cache.

The way to do this is to create a decorated cache and then call cache.setName(new_name) and then add it to CacheManager with CacheManager.addDecoratedCache().

/**
* Adds a decorated {@link Ehcache} to the CacheManager. This method neither
* creates the memory/disk store nor initializes the cache. It only adds the
* cache reference to the map of caches held by this cacheManager.
*
* It is generally required that a decorated cache, once constructed, is made
* available to other execution threads. The simplest way of doing this is to
* either add it to the cacheManager with a different name or substitute the
* original cache with the decorated one.
*
* This method adds the decorated cache assuming it has a different name.
* If another cache (decorated or not) with the same name already exists,
* it will throw {@link ObjectExistsException}. For replacing existing
* cache with another decorated cache having same name, please use
* {@link #replaceCacheWithDecoratedCache(Ehcache, Ehcache)}
*
* Note that any overridden Ehcache methods by the decorator will take on
* new behaviours without casting. Casting is only required for new methods
* that the decorator introduces. For more information see the well known
* Gang of Four Decorator pattern.
*
* @param decoratedCache
* @throws ObjectExistsException
* if another cache with the same name already exists.
*/
public void addDecoratedCache(Ehcache decoratedCache) throws ObjectExistsException {

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

  1. 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 ...

  2. 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 ...

  3. 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 ...

  4. Ehcache(2.9.x) - API Developer Guide, Cache Manager Event Listeners

    About CacheManager Event Listeners CacheManager event listeners allow implementers to register callb ...

  5. Ehcache(2.9.x) - API Developer Guide, Cache Event Listeners

    About Cache Event Listeners Cache listeners allow implementers to register callback methods that wil ...

  6. Ehcache(2.9.x) - API Developer Guide, Cache Exception Handlers

    About Exception Handlers By default, most cache operations will propagate a runtime CacheException o ...

  7. Ehcache(2.9.x) - API Developer Guide, Cache Extensions

    About Cache Extensions Cache extensions are a general-purpose mechanism to allow generic extensions ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. JqueryMobile- 搭建主模板

    最近公司要开发手机端的,可是我没学过安卓,然后用HTML5+JQUERYMOBILE也可以做这些手机端的程序,做成个网页,发到网上,免强也行,于是开始了我JQUERYMOBILE的学习. 先放一下主模 ...

  2. [置顶] iOS开发规范

    iOS代码编程规范 详细讲解代码该如何写,怎样写,如何规范. 什么样的代码是最美的,本文档会给你讲解 iOS代码编程规范........................................ ...

  3. httpclient发送request请求时设置header和timeout

    package com.xxx.xxx.common; import java.io.BufferedReader; import java.io.InputStreamReader; import ...

  4. 一个简单的小例子让你明白c#中的委托-终于懂了!

    模拟主持人发布一个问题,由多个嘉宾来回答这个问题. 分析:从需求中抽出Host (主持人) 类和Guests (嘉宾) 类. 作为问题的发布者,Host不知道问题如何解答.因此它只能发布这个事件,将事 ...

  5. delphi 文件或目录转换成 TreeView

    //文件或目录转换成 TreeViewprocedure DirToTreeView(Tree: TTreeView; Directory: string; Root: TTreeNode; Incl ...

  6. JAVA编程规则

    本附录包含了大量有用的建议,帮助大家进行低级程序设计,并提供了代码编写的一般性指导: (1) 类名首字母应该大写.字段.方法以及对象(句柄)的首字母应小写.对于所有标识符,其中包含的所有单词都应紧靠在 ...

  7. Android-WizardPager

    https://github.com/HeinrichReimer/Android-WizardPager

  8. perl 变量详解

    http://www.perlmonks.org/?node_id=933450 use strict; use Devel::Peek; my $a; Dump($a); $a=4; Dump($a ...

  9. Date Format, 时间戳格式化

    // 对Date的扩展,将 Date 转化为指定格式的String // 月(M).日(d).小时(h).分(m).秒(s).季度(q) 可以用 1-2 个占位符, // 年(y)可以用 1-4 个占 ...

  10. mysql的二级索引

    mysql中每个表都有一个聚簇索引(clustered index ),除此之外的表上的每个非聚簇索引都是二级索引,又叫辅助索引(secondary indexes). 以InnoDB来说,每个Inn ...