About Cache Event Listeners

Cache listeners allow implementers to register callback methods that will be executed when a cache event occurs. Cache listeners implement the CacheEventListener interface. The events include:

  • An Element has been put
  • An Element has been updated. Updated means that an Element exists in the Cache with the same key as the Element being put.
  • An Element has been removed
  • An Element expires, either because timeToLive or timeToIdle have been reached.
Callbacks to these methods are synchronous and unsynchronized. It is the responsibility of the implementer to safely handle the potential performance and thread safety issues depending on what their listener is doing. Listeners are guaranteed to be notified of events in the order in which they occurred. Elements can be put or removed from a Cache without notifying listeners by using the putQuiet() and removeQuiet() methods.

Configuring a Cache Event Listener

Cache event listeners are configured per cache. Each cache can have multiple listeners. Each listener is configured by adding a cacheEventListenerFactory element as follows:

<cache ...>
<cacheEventListenerFactory class="" properties="" listenFor=""/>
...
</cache>

The entry specifies a CacheEventListenerFactory that creates a CacheEventListener, which then receives notifications. The attributes of a CacheEventListenerFactory are:

  • class — a fully qualified factory class name.
  • properties — optional comma-separated properties having meaning only to the factory.
  • listenFor — describes which events will be delivered in a clustered environment (defaults to “all”).

    These are the possible values:

    • "all" — the default is to deliver all local and remote events.
    • "local" — deliver only events originating in the current node.
    • "remote" — deliver only events originating in other nodes (for BigMemory Max only).

Callbacks to listener methods are synchronous and unsynchronized. It is the responsibility of the implementer to safely handle the potential performance and thread safety issues depending on what their listener is doing.

Implementing a Cache Event Listener Factory and Cache Event Listener

A CacheEventListenerFactory is an abstract factory for creating cache event listeners. Implementers should provide their own concrete factory, extending this abstract factory. It can then be configured in ehcache.xml. The following example demonstrates how to create an abstract CacheEventListenerFactory:

/**
* An abstract factory for creating listeners. Implementers should provide their own
* concrete factory extending this factory. It can then be configured in ehcache.xml.
*
* @author Greg Luck
* @version $Id: CacheEventListenerFactory.java 5594 2012-05-07 16:04:31Z cdennis $
*/
public abstract class CacheEventListenerFactory { /**
* Create a <code>CacheEventListener</code>
*
* @param properties implementation specific properties. These are configured as comma
* separated name value pairs in ehcache.xml
* @return a constructed CacheEventListener
*/
public abstract CacheEventListener createCacheEventListener(Properties properties); }

The following example demonstrates how to create a concrete implementation of the CacheEventListener interface:

/**
* Allows implementers to register callback methods that will be executed when a cache event
* occurs.
* The events include:
* <ol>
* <li>put Element
* <li>update Element
* <li>remove Element
* <li>evict Element
* <li>an Element expires, either because timeToLive or timeToIdle has been reached.
* <li>removeAll, which causes all elements to be cleared from the cache
* </ol>
* <p/>
* Callbacks to these methods are synchronous and unsynchronized. It is the responsibility of
* the implementer to safely handle the potential performance and thread safety issues
* depending on what their listener is doing.
* <p/>
* Cache also has putQuiet and removeQuiet methods which do not notify listeners.
*
* @author Greg Luck
* @version $Id: CacheEventListener.java 7439 2013-04-26 19:16:59Z ljacomet $
* @see CacheManagerEventListener
* @since 1.2
*/
public interface CacheEventListener extends Cloneable { /**
* Called immediately after an attempt to remove an element. The remove method will block until
* this method returns.
* <p/>
* This notification is received regardless of whether the cache had an element matching
* the removal key or not. If an element was removed, the element is passed to this method,
* otherwise a synthetic element, with only the key set is passed in.
* <p/>
* This notification is not called for the following special cases:
* <ol>
* <li>removeAll was called. See {@link #notifyRemoveAll(net.sf.ehcache.Ehcache)}
* <li>An element was evicted from the cache.
* See {@link #notifyElementEvicted(net.sf.ehcache.Ehcache, net.sf.ehcache.Element)}
* </ol>
*
* @param cache the cache emitting the notification
* @param element the element just deleted, or a synthetic element with just the key set if
* no element was removed.
*/
void notifyElementRemoved(Ehcache cache, Element element) throws CacheException; /**
* Called immediately after an element has been put into the cache. The
* {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method
* will block until this method returns.
* <p/>
* Implementers may wish to have access to the Element's fields, including value, so the
* element is provided. Implementers should be careful not to modify the element. The
* effect of any modifications is undefined.
*
* @param cache the cache emitting the notification
* @param element the element which was just put into the cache.
*/
void notifyElementPut(Ehcache cache, Element element) throws CacheException; /**
* Called immediately after an element has been put into the cache and the element already
* existed in the cache. This is thus an update.
* <p/>
* The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method
* will block until this method returns.
* <p/>
* Implementers may wish to have access to the Element's fields, including value, so the
* element is provided. Implementers should be careful not to modify the element. The
* effect of any modifications is undefined.
*
* @param cache the cache emitting the notification
* @param element the element which was just put into the cache.
*/
void notifyElementUpdated(final Ehcache cache, final Element element) throws CacheException; /**
* Called immediately after an element is <i>found</i> to be expired. The
* {@link net.sf.ehcache.Cache#remove(Object)} method will block until this method returns.
* <p/>
* Elements are checked for expiry in ehcache at the following times:
* <ul>
* <li>When a get request is made
* <li>When an element is spooled to the diskStore in accordance with a MemoryStore
* eviction policy
* <li>In the DiskStore when the expiry thread runs, which by default is
* {@link net.sf.ehcache.Cache#DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS}
* </ul>
* If an element is found to be expired, it is deleted and this method is notified.
*
* @param cache the cache emitting the notification
* @param element the element that has just expired
* <p/>
* Deadlock Warning: expiry will often come from the <code>DiskStore</code>
* expiry thread. It holds a lock to the DiskStorea the time the
* notification is sent. If the implementation of this method calls into a
* synchronized <code>Cache</code> method and that subsequently calls into
* DiskStore a deadlock will result. Accordingly implementers of this method
* should not call back into Cache.
*/
void notifyElementExpired(final Ehcache cache, final Element element); /**
* Called immediately after an element is evicted from the cache. Evicted in this sense
* means evicted from one store and not moved to another, so that it exists nowhere in the
* local cache.
* <p/>
* In a sense the Element has been <i>removed</i> from the cache, but it is different,
* thus the separate notification.
*
* @param cache the cache emitting the notification
* @param element the element that has just been evicted
*/
void notifyElementEvicted(final Ehcache cache, final Element element); /**
* Called during {@link net.sf.ehcache.Ehcache#removeAll()} to indicate that the all
* elements have been removed from the cache in a bulk operation. The usual
* {@link #notifyElementRemoved(net.sf.ehcache.Ehcache, net.sf.ehcache.Element)}
* is not called.
* <p/>
* This notification exists because clearing a cache is a special case. It is often
* not practical to serially process notifications where potentially millions of elements
* have been bulk deleted.
* @param cache the cache emitting the notification
*/
void notifyRemoveAll(final Ehcache cache); /**
* Creates a clone of this listener. This method will only be called by ehcache before a
* cache is initialized.
* <p/>
* This may not be possible for listeners after they have been initialized. Implementations
* should throw CloneNotSupportedException if they do not support clone.
*
* @return a clone
* @throws CloneNotSupportedException if the listener could not be cloned.
*/
public Object clone() throws CloneNotSupportedException; /**
* Give the listener a chance to cleanup and free resources when no longer needed
*/
void dispose();
}

Two other methods are also available:

  • void notifyElementEvicted(Ehcache cache, Element element)

    Called immediately after an element is evicted from the cache. Eviction, which happens when a cache entry is deleted from a store, should not be confused with removal, which is a result of calling Cache.removeElement(Element).

  • void notifyRemoveAll(Ehcache cache)

    Called during Ehcache.removeAll() to indicate that all elements have been removed from the cache in a bulk operation. The usualnotifyElementRemoved(net.sf.ehcache.Ehcache, net.sf.ehcache.Element) is not called. Only one notification is emitted because performance considerations do not allow for serially processing notifications where potentially millions of elements have been bulk deleted.

The implementations need to be placed in the classpath accessible to Ehcache. For details on how the loading of these classes will be done, see Class Loading.

Adding a Listener Programmatically

To add a listener programmatically, follow this example:

cache.getCacheEventNotificationService().registerListener(myListener);

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

  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 Manager Event Listeners

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

  3. Ehcache(2.9.x) - API Developer Guide, Cache Decorators

    About Cache Decorators Ehcache uses the Ehcache interface, of which Cache is an implementation. It i ...

  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, 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. Umbraco 上传文件到另一个文件夹,而不是media files

    If you want to upload there media files to another place in the same instance of IIS, for example a ...

  2. linux(centos 6)下记录所有用户的操作以及ip、时间

    编辑/etc/profile文件,在文件末尾加入下面代码: [root@iZ23nn1p4mjZ root]# vi /etc/profile history USER=`whoami` USER_I ...

  3. [EntLib]微软企业库5.0 学习之路——第一步、基本入门

    话说在大学的时候帮老师做项目的时候就已经接触过企业库了但是当初一直没明白为什么要用这个,只觉得好麻烦啊,竟然有那么多的乱七八糟的配置(原来我不知道有配置工具可以进行配置,请原谅我的小白). 直到去年在 ...

  4. opennebula 自定义安装目录

    /bin//mkinstalldirs /usr/local/lib /bin//mkinstalldirs /usr/local/include /bin//mkinstalldirs /usr/l ...

  5. 小菜学习MVC4-WebApi

    今天想看下MVC4的东西,发现 居然有WebApi这东西,百度了一下..居然是 WCF中的东西,然后移植到了MVC4中,WCF你懂得返回数据都是xml,向网站这种请求 就比较纠结...而webapi可 ...

  6. BZOJ 3555: [Ctsc2014]企鹅QQ hash

    3555: [Ctsc2014]企鹅QQ Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/p ...

  7. osg 笔记一 (转)

    场景图形采用一种自顶向下的,分层的树状数据结构来组织空间数据集,以提高渲染的效率 场景图形树结构的顶部是一个根节点,从根节点向下延伸,各个组节点中均包含了几何信息和用于控制其外观的渲染状态信息.根节点 ...

  8. 分享一个圆角自定义的漂亮AlertDialog

    \res\drawable-hdpi\bg_title_custom_dialog.xml: <?xml version="1.0" encoding="utf-8 ...

  9. JAVA线程池简介

    一 简介 线程的使用在java中占有极其重要的地位,在jdk1.4极其之前的jdk版本中,关于线程池的使用是极其简陋的.在jdk1.5之后这一情况有了很大的改观.Jdk1.5之后加入了java.uti ...

  10. android150 笔记

    1. 什么是Activity? 四大组件之一,一般的,一个用户交互界面对应一个activity,界面的容器. setContentView() ,// 要显示的布局 button.setOnclick ...