Monitoring remote Infinispan caches with Listeners

Event listeners can be used with Infinispan caches to notify remote clients of events happening on the Cache, such as CacheEntryCreated, CacheEntryModified or CacheEntryRemoved. In this tutorial we’ve learnt how to monitor a local embedded Infinispan cache: Monitoring WildFly’s Infinispan caches.

The following example shows how a remote client, using the Hot Rod protocol, is able to listen and print events happening on the remote cache:

import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated;
import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified;
import org.infinispan.client.hotrod.annotation.ClientListener;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.event.ClientCacheEntryCreatedEvent;
import org.infinispan.client.hotrod.event.ClientCacheEntryModifiedEvent;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;
 
public class RemoteListenerDemo {
 
   public static void main(String[] args) throws InterruptedException {
       
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.addServer().host("192.168.10.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
       
      RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
       
      RemoteCache<String, String> cache = cacheManager.getCache();
       
      BasicListener listener = new BasicListener();
      cache.addClientListener(listener);
       
      cache.put("entry1", "value1");
      cache.put("entry2", "value2");
      cache.put("entry3", "value3");
      
      Thread.sleep(1000);
       
      cache.removeClientListener(listener);
       
      cacheManager.stop();
   }
 
   @ClientListener
   public static class BasicListener {
 
      @ClientCacheEntryCreated
      public void entryCreated(ClientCacheEntryCreatedEvent<String> event) {
         System.out.printf("Created %s%n", event.getKey());
      }
 
      @ClientCacheEntryModified
      public void entryModified(ClientCacheEntryModifiedEvent<String> event) {
         System.out.printf("Going to modify %s%n", event.getKey());
      }
 
   }
 
}

The expected output will be:

ClientCacheEntryCreatedEvent(key=entry1,dataVersion=1)
ClientCacheEntryCreatedEvent(key=entry2,dataVersion=1)
ClientCacheEntryCreatedEvent(key=entry3,dataVersion=1)

Please note that the actual value is not sent back to the client for performance reasons. As a matter of fact, receiving remote events has a performance impact, which increases as the cache size grows. In order to avoid bottlenecks to Hot Rod remote clients, it is recommended to filter remote events on the server side.

Found the article helpful? if so please follow us on Socials