Per-Cache Configuration

What You Will Learn

How to define per-cache configuration on the Hot Rod client using three different approaches: server-side templates, inline XML strings, and XML files loaded from a URI. When you call getCache() for a cache that does not yet exist, Infinispan creates it automatically from the provided configuration.

Prerequisites

  • Java 17+

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

Step 1: Define Per-Cache Configurations

You can configure caches using a template name, an inline XML string, or an XML file loaded from a URI. Register templates on the server before first cache access:

      // Add per-cache configuration that uses an org.infinispan cache template.
      builder.remoteCache(MY_CACHE)
               // we can declare a template, even if the template does not exist yet.
               // however, the template has to be present on first access to create the cache.
              .templateName(MY_CUSTOM_TEMPLATE);

      // Add per-cache configuration with a cache definition in XML format.
      builder.remoteCache(ANOTHER_CACHE)
              .configuration("<distributed-cache name=\"another-cache\"><encoding media-type=\"application/x-protostream\"/></distributed-cache>");

      // Load cache definition from a classpath XML file URI.
      builder.remoteCache(URI_CACHE).configurationURI(
              InfinispanRemotePerCache.class.getClassLoader().getResource("cacheConfig.xml").toURI());

      cacheManager = TutorialsConnectorHelper.connect(builder);

      // Create the template that is used to create MY-CACHE on first access
      cacheManager.administration().removeTemplate(MY_CUSTOM_TEMPLATE);
      cacheManager.administration().createTemplate(MY_CUSTOM_TEMPLATE, new StringConfiguration("<distributed-cache><encoding media-type=\"application/x-protostream\"/></distributed-cache>"));

The cacheConfig.xml file referenced by the URI configuration contains:

<distributed-cache name="uri-cache">
    <encoding media-type="application/x-protostream"/>
</distributed-cache>

Step 2: Use the Caches

All three caches are created on first access via getCache():

      // Obtain a remote cache that does not exist.
      // Rather than return null, create the cache from a template.
      cache = cacheManager.getCache(MY_CACHE);
      /// Store a value
      cache.put("hello", "world");
      // Retrieve the value and print it out
      System.out.printf("key = %s\n", cache.get("hello"));

Step 3: Run the Tutorial

mvn package exec:java

You should see output like:

key = world
key = world-another
key = world-uri

What’s Next