Coherence Cache Listener Java Example

Oracle coherence cache provides many functionality and creating listener on any cache one of the most frequently used functionality in cache. In this functionality you can create cache listener to any cache which will listen any changes to the cache like if any Update, Insert or Delete happen on the cache. Below example is individual java program which will listen change to “Product” cache and hit individual overridden method so that you could perform action based on the changes:

  • CoherenceCacheListener.java:
package com.wfs.otc.cache;

import java.util.Set;

import com.tangosol.net.NamedCache;
import com.tangosol.util.MapEvent;
import com.tangosol.util.MapListener;
import com.javahonk.datautil.CacheRegistry;

public class CoherenceCacheListener implements MapListener {
	
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) {
		
		System.setProperty("javahonk.ccu.clientconfig", "extend-access.xml");
		System.setProperty("javahonk.ccu.url", "http://URL.com/clusterclient/clustername/server/");	
		System.setProperty("javahonk.cluster.extend.access", "true");
		System.setProperty("javahonk.ccu.serializer.config", "http://URL.com/clustername/");
		System.setProperty("tangosol.pof.enabled", "true");
		System.setProperty("tangosol.pof.config", "custom-types-pof-config.xml");
		System.setProperty("logging.dir", "./");
		
		NamedCache cache = (NamedCache) CacheRegistry.getNamedCache("Products");
		
		Set value = cache.keySet();
		
		for (Object object : value) {
			System.out.println("Key:"+object.toString());
			System.out.println("Value:"+cache.get(object));
		}
		
		System.out.println(cache.size());
		
		cache.addMapListener(new CoherenceCacheListener());
		
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {			 
			@Override
			public void run() {				
				while (!Thread.interrupted()){}
			}
		}));
	}
	
	@Override
	public void entryDeleted(MapEvent arg0) {
		System.out.println(arg0);
		
	}

	@Override
	public void entryInserted(MapEvent arg0) {
		System.out.println(arg0);
		
	}

	@Override
	public void entryUpdated(MapEvent arg0) {
		System.out.println(arg0);
		
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *