How to iterate over an Infinispan cache

In this tutorial, we will explore how to iterate over an Infinispan cache. We’ll cover the necessary steps to set up a cache manager, create a replicated synchronous cache, store data, and iterate over the cache entries.

Prerequisites

Before getting started, ensure that you have the following prerequisites:

  • JDK (Java Development Kit) installed on your machine.
  • Infinispan library added to your project dependencies.

Iterating over an Infinispan Replicated Cache

The following example shows how to add some random keys/values in a replicated cache and then Iterate over the Cache:

import org.infinispan.Cache;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.context.Flag;
import org.infinispan.manager.DefaultCacheManager;

import java.util.UUID;

public class InfinispanReplicated {

   public static void main(String[] args) throws Exception {

      GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();

      DefaultCacheManager cacheManager = new DefaultCacheManager(global.build());
      // Create a replicated synchronous configuration
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.clustering().cacheMode(CacheMode.REPL_SYNC);
      Configuration cacheConfig = builder.build();
      // Create a cache
      Cache<String, String> cache = cacheManager.administration()
              .withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
              .getOrCreateCache("cache", cacheConfig);

      // Store the current node address in some random keys
      for(int i=0; i < 10; i++) {
         cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
      }
      // Display the current cache contents for the whole cluster
      cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
      // Display the current cache contents for this node
      cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
         .entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
      // Stop the cache manager and release all resources
      cacheManager.stop();
   }

}

As you can see, we are doing two types of iterations:

  • An iteration over the whole cluster with a plain cache.entrySet().forEach Loop
  • An iteration over the Local Infinispan Node with a cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP) .entrySet().forEach

Iterating over a Distributed Cache

The iteration over a Distributed Cache is slightly different from the Replicated one:

public class InfinispanDistributed {

   public static void main(String[] args) throws Exception {
      // Setup up a clustered cache manager
      GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
      // Initialize the cache manager
      DefaultCacheManager cacheManager = new DefaultCacheManager(global.build());
      //Create cache configuration
      ConfigurationBuilder builder = new ConfigurationBuilder();
      builder.clustering().cacheMode(CacheMode.DIST_SYNC);
      // Obtain a cache
      Cache<String, String> cache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
            .getOrCreateCache("cache", builder.build());

      // Store the current node address in some random keys
      for (int i = 0; i < 10; i++) {
         cache.put(UUID.randomUUID().toString(), cacheManager.getNodeAddress());
      }
      // Display the current cache contents for the whole cluster
      cache.entrySet().forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
      // Display the current cache contents for this node
      // Note: By default numOwners=2, so in a cluster with 2 nodes, each node owns all the keys:
      // some of the keys as "primary owner" and some keys as "backup owner"
      cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).entrySet()
            .forEach(entry -> System.out.printf("%s = %s\n", entry.getKey(), entry.getValue()));
      // Stop the cache manager and release all resources
      cacheManager.stop();
   }

}

As you can see, looping over the whole cluster is identical with the replicated example. On the other hand, you can iterate over the Local Node Cache with cache.getAdvancedCache().withFlags(Flag.CACHE_MODE_LOCAL).entrySet() .forEach

Conclusion

In this tutorial, we covered how to iterate over a replicated Infinispan cache. We learned how to set up a cache manager, create a replicated synchronous cache, store.

Source code:

https://github.com/infinispan/infinispan-simple-tutorials/blob/main/infinispan-embedded/cache-replicated/src/main/java/org/infinispan/tutorial/simple/replicated/InfinispanReplicated.java

https://github.com/infinispan/infinispan-simple-tutorials/blob/main/infinispan-embedded/cache-distributed/src/main/java/org/infinispan/tutorial/simple/distributed/InfinispanDistributed.java

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