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)

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.
Tip
If no server is running, the tutorial code automatically starts an Infinispan Server using 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