Remote Cache Administration

What You Will Learn

How to create remote caches programmatically using the Hot Rod admin API. You will create caches with no configuration, from a template, and from XML configuration.

Prerequisites

  • Java 17+

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

Step 1: Add the Hot Rod Client Dependency

Add the Infinispan Hot Rod client to your pom.xml:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-client-hotrod</artifactId>
</dependency>

Step 2: Create a Simple Cache

Use the admin API to create a cache with no configuration:

        try {
            cacheManager.administration().createCache(SIMPLE_CACHE, (String)null);
            System.out.println("SimpleCache created.");
        } catch (Exception e) {
            System.out.println("Expected to fail for multiple invocations as the cache exists message: " + e.getMessage());
        }

If the cache already exists, createCache throws an exception. Use getOrCreateCache instead for idempotent creation.

Step 3: Create Caches from Templates and XML

You can also create caches from a registered template or a full XML cache definition using StringConfiguration.

Define a cache template in XML:

<infinispan>
    <cache-container>
        <distributed-cache-configuration name="template" remote-timeout="17500" statistics="true">
            <locking acquire-timeout="15000" striping="false" concurrency-level="1000"/>
            <encoding media-type="application/x-protostream"/>
            <state-transfer timeout="60000"/>
        </distributed-cache-configuration>
    </cache-container>
</infinispan>

Then register the template and create caches using both approaches:

        // Create a cache from a template
        Path path = Paths.get(InfinispanRemoteAdminCache.class.getClassLoader().getResource("cacheTemplate.xml").getPath());
        String xmlTemplate = Files.readString(path);
        try {
            cacheManager.administration().createTemplate("template", new StringConfiguration(xmlTemplate));
        } catch (Exception ce) {
            System.out.println(ce.getMessage());
        }
        cacheManager.administration().getOrCreateCache(CACHE_WITH_TEMPLATE, "template");

        // Create a cache with full XML configuration
        String xml = Files.readString(Paths.get(InfinispanRemoteAdminCache.class.getClassLoader().getResource("CacheWithXMLConfiguration.xml").getPath()));
        cacheManager.administration().getOrCreateCache(CACHE_WITH_XMLCONFIGURATION, new StringConfiguration(xml));

The XML cache definition file (CacheWithXMLConfiguration.xml) specifies the full cache configuration including encoding, locking, transactions, and expiration settings.

Step 4: Run the Tutorial

mvn package exec:java

You should see output like:

SimpleCache created.
Cache created from default template.
Cache with configuration exists or is created.

What’s Next