Client Listeners for Cache Events

What You Will Learn

How to register a @ClientListener on a remote cache to receive asynchronous notifications when entries are created or modified.

Prerequisites

  • Java 17+

  • An Infinispan Server running on localhost:11222 (or Docker/Podman available for Testcontainers)

Step 1: Define a Client Listener

Create a class annotated with @ClientListener and add methods annotated with @ClientCacheEntryCreated and @ClientCacheEntryModified:

   @ClientListener
   public static class MyListener {
      StringBuilder logTrack = new StringBuilder();

      @ClientCacheEntryCreated
      public void entryCreated(ClientCacheEntryCreatedEvent<String> event) {
         String logMessage = String.format("Created %s%n", event.getKey());
         logTrack.append(logMessage);
         System.out.printf(logMessage);
      }

      @ClientCacheEntryModified
      public void entryModified(ClientCacheEntryModifiedEvent<String> event) {
         String logMessage = String.format("About to modify %s%n", event.getKey());
         logTrack.append(logMessage);
         System.out.printf(logMessage);
      }

   }

After connecting to the server, register the listener on a remote cache with cache.addClientListener(new MyListener()).

Step 2: Trigger Events and Clean Up

Store and update entries to generate events. Always remove listeners when they are no longer needed:

      // Store some values
      cache.put("key1", "value1");
      cache.put("key2", "value2");
      cache.put("key1", "newValue");

      // Remote events are asynchronous, so allow a short wait before removing
      // Remove listener when no longer needed
      cache.removeClientListener(listener);

Remote events are asynchronous, so allow a short wait before shutting down.

Step 3: Run the Tutorial

mvn package exec:java

You should see output like:

Created key1
Created key2
About to modify key1

What’s Next