Cache Encodings with DataFormat

What You Will Learn

How to configure caches with different media type encodings (text/plain, JSON, XML) and use the DataFormat API to read and write data with a UTF8StringMarshaller.

Prerequisites

  • Java 17+

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

Step 1: Define Cache Configurations and Connect

Create XML cache configurations for each encoding (text/plain, JSON, XML) and load them when connecting:

      ConfigurationBuilder builder = TutorialsConnectorHelper.connectionConfig();

      URI textCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("textCache.xml").toURI();
      URI jsonCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("jsonCache.xml").toURI();
      URI xmlCacheURI = InfinispanEncodingCaches.class.getClassLoader().getResource("xmlCache.xml").toURI();

      builder.remoteCache("textCache").configurationURI(textCacheURI);
      builder.remoteCache("jsonCache").configurationURI(jsonCacheURI);
      builder.remoteCache("xmlCache").configurationURI(xmlCacheURI);

      cacheManager = TutorialsConnectorHelper.connect(builder);

For JSON and XML caches, use DataFormat to specify the marshaller and media type when obtaining cache references. The text cache works directly with the default marshaller.

Step 2: Store and Retrieve Data

Put and get values using each cache with its respective encoding:

      System.out.println("== Cache with text encoding and string marshaller.");
      textCache.put("text", "诶, 你好.");
      System.out.println("Get key from text cache: " + textCache.get("text"));

      System.out.println("== Cache with json encoding and string marshaller.");
      jsonCache.put("\"json\"", "{\"name\": \"infinispan\"}");
      System.out.println("Get key from json cache: " + jsonCache.get("json"));

      System.out.println("== Cache with xml encoding and string marshaller.");
      xmlCache.put("xml", "<name>infinispan</name>");
      System.out.println("Get key from xml cache: " + xmlCache.get("xml"));

Step 3: Run the Tutorial

mvn package exec:java

What’s Next