Step 6: Listen to changes in the cluster

In the previous step we successfully started a cluster with two nodes, but we had very little control over the lifecycle of the cluster and both nodes effectively performed the same operations. In this step we will look into cluster events and how they can help in making sure things happen predictably when the cluster topology changes. In order to listen to specific events, we need to create and attach a listener to the CacheManager. An Infinispan listener is simply a class annotated with @Listener. You choose which events you will be notified about by adding annotated methods, e.g.:

@Listener
public class ClusterListener {
  @ViewChanged
  public void viewChanged(ViewChangedEvent event) {
  }
}
In the above example we will be notified whenever a node leaves or joins the cluster. The event object will contain detailed information about the previous topology, the new topology, etc. In our WeatherApp we will be using that information alongside two CountdownLatch instances: one that waits for the expected number of nodes to form the initial cluster, and one that allows a node to shutdown only when the original coordinator node has left the cluster.
$ git checkout -f step-6
$ mvn clean package exec:exec # from terminal 1
$ mvn exec:exec # from terminal 2

This time the first node you start will wait for the second node to join the cluster before proceeding with its job. In the next step we will be looking at another type of events: Cache events.

back to top