Search

Chapter 33. Integration with the Spring Framework

download PDF

Red Hat JBoss Data Grid provides integration with the Spring Framework through a set of modules that enable you to use JBoss Data Grid as a cache provider.

33.1. Enabling Spring Cache Support

The first step to integrating Red Hat JBoss Data Grid with Spring is to enable cache support in the application context. This step lets you use the @Cacheable and @CacheEvict annotations for adding and removing entries from the cache.

33.1.1. Declaratively Enabling Spring Cache Support

To declaratively enable Spring cache support, add <cache:annotation-driven/> to the application context, as in the following example:

<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 />

33.1.2. Programmatically Enabling Spring Cache Support

Programmatically enable Spring cache support as follows:

@EnableCaching @Configuration
public class Config {
}

33.2. Adding the Spring Integration Module

Add the appropriate dependencies for Red Hat JBoss Data Grid and the Spring integration module to your pom.xml as follows:

Library mode
<dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-spring4-embedded</artifactId>
    <version>${version.spring}</version>
</dependency>
Remote Client-Server mode
<dependency>
    <groupId>org.infinispan</groupId>
    <artifactId>infinispan-spring4-remote</artifactId>
    <version>${version.spring}</version>
</dependency>

33.3. Configuring Red Hat JBoss Data Grid as the Spring Caching Provider

The Spring cache provider SPI has two interfaces through which it interacts with Red Hat JBoss Data Grid, org.springframework.cache.CacheManager and org.springframework.cache.Cache. The CacheManager interface acts as a factory for named Cache instances.

To use JBoss Data Grid acts as the caching provider, the Spring Framework requires a CacheManager implementation with a bean named cacheManager in the application context.

The following examples show how you can configure your application context either declaratively or programmatically:

33.3.1. Declaratively Configuring JBoss Data Grid as the Spring Caching Provider

Library mode
<bean id="cacheManager"          class="org.infinispan.spring.provider.SpringEmbeddedCacheManagerFactoryBean"
         p:configurationFileLocation="classpath:/path/to/cache-config.xml" />
Remote Client-Server mode
<bean id="cacheManager"          class="org.infinispan.spring.provider.SpringRemoteCacheManagerFactoryBean"
         p:configurationFileLocation="classpath:/path/to/hotrod-client.properties" />

33.3.2. Programmatically Configuring JBoss Data Grid as the Spring Caching Provider

Library mode
@EnableCaching
@Configuration
public class Config {

   @Bean
   public CacheManager cacheManager() {
      return new SpringEmbeddedCacheManager(infinispanCacheManager());
   }

   private EmbeddedCacheManager infinispanCacheManager() {
      return new DefaultCacheManager();
   }

}
Remote Client-Server mode
@EnableCaching
@Configuration
public class Config {

   @Bean
   public CacheManager cacheManager() {
      return new SpringRemoteCacheManager(infinispanCacheManager());
   }

   private RemoteCacheManager infinispanCacheManager() {
      return new DefaultCacheManager();
   }

}

33.4. Adding Caching to Your Application Code

You can add caching to your application with Spring annotations.

Adding Cache Entries

To add entries to the cache add the @Cacheable annotation to select methods. This annotation will add any returned values to the indicated cache. For instance, consider a method that returns a Book based on a particular key.

By annotating this method with @Cacheable:

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

Any Book instances returned from findBook(Integer bookId) will be placed in a named cache books, using the bookId as the value’s key.

Important

If the key attribute is not specified then Spring will generate a hash from the supplied arguments and use this generated value as the cache key. If your application needs to reference the entries directly it is recommended to include the key attribute so that entries may be easily obtained.

Deleting Cache Entries

To remove entries from the cache annotate the desired methods with @CacheEvict. This annotation can be configured to evict all entries in a cache, or to only affect entries with the indicated key. Consider the following examples:

// Evict all entries in the "books" cache
@Transactional
@CacheEvict (value="books", key = "#bookId", allEntries = true)
public void deleteBookAllEntries() {...}

// Evict any entries in the "books" cache that match the passed in bookId
@Transactional
@CacheEvict (value="books", key = "#bookId")
public void deleteBook(Integer bookId) {...]}

33.5. Configuring Timeouts for Cache Operations

The Red Hat JBoss Data Grid Spring Cache provider defaults to blocking behaviour when performing read and write operations. By default operations are synchronous and do not time out. However, you might want to set a maximum time to wait for operations before timing out in some situations. For example, timeouts are useful if you need to ensure that an operation completes within a certain time and you can ignore the cached value.

The following properties let you set timeouts for read and write operations:

  • 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.

To configure timeouts for cache operations, set the properties in the context XML for your application on either SpringEmbeddedCacheManagerFactoryBean or SpringRemoteCacheManagerFactoryBean as follows:

Library mode
<bean id="springEmbeddedCacheManagerConfiguredUsingConfigurationProperties" class="org.infinispan.spring.provider.SpringEmbeddedCacheManagerFactoryBean">
    <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>
Remote Client-Server mode
<bean id="springRemoteCacheManagerConfiguredUsingConfigurationProperties" class="org.infinispan.spring.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>
Note

In remote client-server mode you can also set these properties in hotrod-client.properties.

33.6. Externalizing Sessions to Red Hat JBoss Data Grid Clusters

Spring Session lets you externalize user session information to JBoss Data Grid in both library mode and remote client-server mode.

To configure Spring Session integration in your application, do the following:

  1. Add the following dependencies to your pom.xml:

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

    • Library mode: SpringEmbeddedCacheManagerFactoryBean
    • Remote Client-Server mode: SpringRemoteCacheManagerFactoryBean
  3. Enable Spring Session with the appropriate annotation.

    • Library mode: @EnableInfinispanEmbeddedHttpSession
    • Remote Client-Server mode: @EnableInfinispanRemoteHttpSession

      These annotations have the following 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 provides an example configuration for JBoss Data Grid in library mode:

@EnableInfinispanEmbeddedHttpSession
@Configuration
public class Config {

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

   //An optional configuration bean that replaces the default cookie
   //for obtaining configuration.
   //For more information refer to Spring Session documentation.
   @Bean
   public HttpSessionStrategy httpSessionStrategy() {
      return new HeaderHttpSessionStrategy();
   }
}
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.