Remote Multimap Cache

What You Will Learn

How to use the remote multimap cache to associate multiple values with a single key, useful for one-to-many relationships.

Prerequisites

  • Java 17+

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

Step 1: Get the Multimap Cache Manager

Connect to the server and obtain a MultimapCacheManager:

      // Connect to the server and create a cache
      cacheManager = TutorialsConnectorHelper.connect();

      // Retrieve the MultimapCacheManager from the CacheManager.
      multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager);

      // Retrieve the multimap cache.
      multimap = multimapCacheManager.get(TUTORIAL_CACHE_NAME);

Step 2: Store Multiple Values per Key

Use put to add multiple values under the same key:

      multimap.put(2016, "Rosita");
      multimap.put(2016, "Guillermo");
      multimap.put(2016, "Patricia");
      multimap.put(2016, "Silvia");
      multimap.put(2017, "Matilda");
      multimap.put(2017, "Hector");
      multimap.put(2018, "Richard").get(10, TimeUnit.SECONDS);

Step 3: Retrieve All Values for a Key

Use get to retrieve the collection of values associated with a key:

      multimap.get(2016).whenComplete((v, ex) -> {
         System.out.println(v);
      }).join();

This prints all four values stored under key 2016.

Step 4: Run the Tutorial

mvn package exec:java

You should see output like:

[Rosita, Guillermo, Patricia, Silvia]

What’s Next