Using Data Grid with Spring

Red Hat Data Grid 8.4

Add Data Grid to Spring applications

Red Hat Customer Content Services

Abstract

Add Data Grid caching capabilities to Spring-based applications.

Red Hat Data Grid

Data Grid is a high-performance, distributed in-memory data store.

Schemaless data structure
Flexibility to store different objects as key-value pairs.
Grid-based data storage
Designed to distribute and replicate data across clusters.
Elastic scaling
Dynamically adjust the number of nodes to meet demand without service disruption.
Data interoperability
Store, retrieve, and query data in the grid from different endpoints.

Data Grid documentation

Documentation for Data Grid is available on the Red Hat customer portal.

Data Grid downloads

Access the Data Grid Software Downloads on the Red Hat customer portal.

Note

You must have a Red Hat account to access and download Data Grid software.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message.

Chapter 1. Using Data Grid as a Spring Cache provider

Add Data Grid dependencies to your application and use Spring Cache annotations to store data in embedded or remote caches.

1.1. Setting up Spring caching with Data Grid

Add the Data Grid dependencies to your Spring application project. If you use remote caches in a Data Grid Server deployment, you should also configure your Hot Rod client properties.

Important

Data Grid supports Spring version 5 and version 6. Be aware that Spring 6 requires Java 17.

The examples in this document include artifacts for the latest version of Spring. If you want to use Spring 5 use:

  • Remote caches: infinispan-spring5-remote
  • Embedded caches: infinispan-spring5-embedded

Procedure

  1. Add Data Grid and the Spring integration module to your pom.xml.

    • Remote caches: infinispan-spring6-remote
    • Embedded caches: infinispan-spring6-embedded

      Tip

      Spring Boot users can add the following artifacts instead of the infinispan-spring6-embedded:

      • For Spring Boot 3 add infinispan-spring-boot3-starter-embedded
      • For Spring Boot 2.x add infinispan-spring-boot-starter-embedded
  2. Configure your Hot Rod client to connect to your Data Grid Server deployment in the hotrod-client.properties file.

    infinispan.client.hotrod.server_list = 127.0.0.1:11222
    infinispan.client.hotrod.auth_username=admin
    infinispan.client.hotrod.auth_password=changeme

Spring Cache dependencies

Remote caches

<dependencies>
    <dependency>
        <groupId>org.infinispan</groupId>
        <artifactId>infinispan-spring6-remote</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${version.spring}</version>
    </dependency>
</dependencies>

Embedded caches

<dependencies>
    <dependency>
        <groupId>org.infinispan</groupId>
        <artifactId>infinispan-spring6-embedded</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${version.spring}</version>
    </dependency>
</dependencies>

1.2. Using Data Grid as a Spring Cache provider

Add the @EnableCaching annotation to one of your configuration classes and then add the @Cacheable and @CacheEvict annotations to use remote or embedded caches.

Prerequisites

  • Add the Data Grid dependencies to your application project.
  • Create the required remote caches and configure Hot Rod client properties if you use a Data Grid Server deployment.

Procedure

  1. Enable cache annotations in your application context in one of the following ways:

    Declarative

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:cache="http://www.springframework.org/schema/cache"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    
            <cache:annotation-driven />
    
    </beans>

    Programmatic

    @EnableCaching @Configuration
    public class Config {
    }

  2. Annotate methods with @Cacheable to cache return values.

    Tip

    To reference entries in the cache directly, you must include the key attribute.

  3. Annotate methods with @CacheEvict to remove old entries from the cache.

1.3. Spring Cache annotations

The @Cacheable and @CacheEvict annotations add cache capabilities to methods.

@Cacheable
Stores return values in a cache.
@CacheEvict
Controls cache size by removing old entries.

@Cacheable

Taking Book objects as an example, if you want to cache each instance after loading it from a database with a method such as BookDao#findBook(Integer bookId), you could add the @Cacheable annotation as follows:

@Transactional
@Cacheable(value = "books", key = "#bookId")
public Book findBook(Integer bookId) {...}

With the preceding example, when findBook(Integer bookId) returns a Book instance it gets stored in the cache named books.

@CacheEvict

With the @CacheEvict annotation, you can specify if you want to evict the entire books cache or only the entries that match a specific #bookId.

Entire cache eviction

Annotate the deleteAllBookEntries() method with @CacheEvict and add the allEntries parameter as follows:

@Transactional
@CacheEvict (value="books", key = "#bookId", allEntries = true)
public void deleteAllBookEntries() {...}

Entry based eviction

Annotate the deleteBook(Integer bookId) method with @CacheEvict and specify the key associated to the entry as follows:

@Transactional
@CacheEvict (value="books", key = "#bookId")
public void deleteBook(Integer bookId) {...}

1.4. Configuring timeouts for cache operations

The Data Grid Spring Cache provider defaults to blocking behaviour when performing read and write operations. Cache operations are synchronous and do not time out.

If necessary you can configure a maximum time to wait for operations to complete before they time out.

Procedure

  • Configure the following timeout properties in the context XML for your application on either SpringEmbeddedCacheManagerFactoryBean or SpringRemoteCacheManagerFactoryBean.

    For remote caches, you can also add these properties to the hotrod-client.properties file.

PropertyDescription

infinispan.spring.operation.read.timeout

Specifies the time, in milliseconds, to wait for read operations to complete. The default is 0 which means unlimited wait time.

infinispan.spring.operation.write.timeout

Specifies the time, in milliseconds, to wait for write operations to complete. The default is 0 which means unlimited wait time.

The following example shows the timeout properties in the context XML for SpringRemoteCacheManagerFactoryBean:

<bean id="springRemoteCacheManagerConfiguredUsingConfigurationProperties"
      class="org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean">
    <property name="configurationProperties">
        <props>
           <prop key="infinispan.spring.operation.read.timeout">500</prop>
           <prop key="infinispan.spring.operation.write.timeout">700</prop>
        </props>
    </property>
</bean>

Chapter 2. Externalizing sessions with Spring Session

Store session data for Spring applications in Data Grid caches and independently of the container.

2.1. Externalizing Sessions with Spring Session

Use the Spring Session API to externalize session data to Data Grid.

Procedure

  1. Add dependencies to your pom.xml.

    • Embedded caches: infinispan-spring6-embedded
    • Remote caches: infinispan-spring6-remote

      The following example is for remote caches:

      <dependencies>
          <dependency>
              <groupId>org.infinispan</groupId>
              <artifactId>infinispan-core</artifactId>
          </dependency>
          <dependency>
              <groupId>org.infinispan</groupId>
              <artifactId>infinispan-spring6-remote</artifactId>
          </dependency>
          <dependency>
              <groupId>org.springframework</groupId>
              <artifactId>spring-context</artifactId>
              <version>${version.spring}</version>
          </dependency>
          <dependency>
             <groupId>org.springframework.session</groupId>
             <artifactId>spring-session-core</artifactId>
             <version>${version.spring}</version>
         </dependency>
         <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-web</artifactId>
             <version>${version.spring}</version>
         </dependency>
      </dependencies>
  2. Specify the appropriate FactoryBean to expose a CacheManager instance.

    • Embedded caches: SpringEmbeddedCacheManagerFactoryBean
    • Remote caches: SpringRemoteCacheManagerFactoryBean
  3. Enable Spring Session with the appropriate annotation.

    • Embedded caches: @EnableInfinispanEmbeddedHttpSession
    • Remote caches: @EnableInfinispanRemoteHttpSession

      These annotations have optional parameters:

      • maxInactiveIntervalInSeconds sets session expiration time in seconds. The default is 1800.
      • cacheName specifies the name of the cache that stores sessions. The default is sessions.

The following example shows a complete, annotation-based configuration:

@EnableInfinispanEmbeddedHttpSession
@Configuration
public class Config {

   @Bean
   public SpringEmbeddedCacheManagerFactoryBean springCacheManager() {
      return new SpringEmbeddedCacheManagerFactoryBean();
   }

   //An optional configuration bean responsible for replacing the default
   //cookie that obtains configuration.
   //For more information refer to the Spring Session documentation.
   @Bean
   public HttpSessionIdResolver httpSessionIdResolver() {
       return HeaderHttpSessionIdResolver.xAuthToken();
   }
}

Legal Notice

Copyright © 2024 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.