Cache Event Listeners with the JavaScript Client
What You Will Learn
How to register event listeners on a cache to receive notifications when entries are created, modified, or removed.
Prerequisites
-
Node.js 22+
-
An Infinispan Server running on
localhost:11222
Start an Infinispan Server with Docker or Podman:
docker run -it --rm -p 11222:11222 -e USER=admin -e PASS=password quay.io/infinispan/server:latest
|
Tip
|
You can replace docker with podman in the command above if you use Podman.
|
Step 1: Register a Listener
Add a listener for create events. The returned listenerId is used to add more event types to the same listener:
const listenerId = await client.addListener('create', (key, version, id) => {
console.log('[CREATE] key=' + key);
});
Step 2: Add More Event Types
Register modify and remove callbacks on the same listener by passing the listenerId:
await client.addListener('modify', (key, version, id) => {
console.log('[MODIFY] key=' + key);
}, {listenerId: listenerId});
await client.addListener('remove', (key, id) => {
console.log('[REMOVE] key=' + key);
}, {listenerId: listenerId});
Step 3: Trigger Events
Cache operations now trigger the registered callbacks:
await client.put('player1', 'Mario'); // triggers CREATE
await client.replace('player1', 'Peach'); // triggers MODIFY
await client.remove('player1'); // triggers REMOVE
Step 4: Remove the Listener
Remove the listener to stop receiving events:
await client.removeListener(listenerId);
Step 5: Run the Tutorial
npm run listeners
You should see output like:
Listener registered: <listener-id> [CREATE] key=player1 [CREATE] key=player2 [MODIFY] key=player1 [REMOVE] key=player2 Listener removed. No events after listener removal.
What’s Next
-
Basic cache operations for standard cache usage
-
Near caching for client-side caching with server invalidation


