Implementing Cache Event Handlers

Depending on your installation and configuration, cache events can come from local operations, peers, servers, and remote sites. Event handlers register their interest in one or more events and are notified when the events occur.

For each type of handler, GemFire provides a convenience class with empty stubs for the interface callback methods.
  1. Decide which events your application needs to handle. For each region, decide which events you want to handle. For the cache, decide whether to handle transaction events.
  2. For each event, decide which handlers to use. The *Listener and *Adapter classes in com.gemstone.gemfire.cache.util show the options.
  3. Program each event handler:

    1. Extend the handler's adapter class.
    2. If you want to declare the handler in the cache.xml, implement the com.gemstone.gemfire.cache.Declarable interface as well.
    3. Implement the handler's callback methods as needed by your application.
      Note: Improperly programmed event handlers can block your distributed system. Cache events are synchronous. To modify your cache or perform distributed operations based on events, avoid blocking your system by following the guidelines in How to Safely Modify the Cache from an Event Handler Callback.
      package myPackage;
      import com.gemstone.gemfire.cache.Declarable;
      import com.gemstone.gemfire.cache.EntryEvent;
      import com.gemstone.gemfire.cache.util.CacheListenerAdapter;
      import java.util.Properties;
      public class MyCacheListener extends CacheListenerAdapter implements Declarable {
      /** Processes an afterCreate event.
       * @param event The afterCreate EntryEvent received
        public void afterCreate(EntryEvent event) {
          String eKey = event.getKey();
          String eVal = event.getNewValue();
            ... do work with event info
          ... process other event types                     
  4. Install the event handlers, either through the API or the cache.xml.

    XML Region Event Handler Installation:

    <region name="trades">
      <region-attributes ... >
        <!-- Cache listener -->

    Java Region Event Handler Installation:

    RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION);
    rf.addCacheListener(new MyCacheListener());
    tradesRegion = rf.create("trades");

    XML Transaction Writer and Listener Installation:

    <cache search-timeout="60">
    			    <parameter name="URL">
    	     	. . . 
    			    <parameter name="URL">
    	  . . . 

The event handlers are initialized automatically during region creation when you start the member.