JCache (JSR-107) with Embedded Infinispan

What You Will Learn

How to use the standard JCache (JSR-107) API with Infinispan as the caching provider. This approach uses the javax.cache API, making your code portable across JCache-compliant implementations.

Prerequisites

  • Java 17+

Step 1: Add the JCache Dependencies

Add both the Infinispan JCache module and the JCache API to your pom.xml:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-jcache</artifactId>
</dependency>
<dependency>
   <groupId>javax.cache</groupId>
   <artifactId>cache-api</artifactId>
</dependency>

Step 2: Create a Cache Using JCache API

Obtain a CachingProvider and CacheManager through the standard JCache SPI, then create a typed cache:

      // Construct a simple local cache manager with default configuration
      jcacheProvider = Caching.getCachingProvider();
      cacheManager = jcacheProvider.getCacheManager();
      MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
      configuration.setTypes(String.class, String.class);
      // create a cache using the supplied configuration
      cache = cacheManager.createCache("myCache", configuration);

Infinispan is automatically discovered as the JCache provider on the classpath.

Step 3: Use the Cache

Store and retrieve values using the standard JCache API:

      // Store a value
      cache.put("key", "value");
      // Retrieve the value and print it out
      System.out.printf("key = %s\n", cache.get("key"));

Step 4: Run the Tutorial

mvn package exec:java

The output shows the stored value retrieved through the JCache API.

What’s Next