Spring Boot HTTP Sessions with Remote Infinispan

What You Will Learn

How to store Spring Boot HTTP sessions in a remote Infinispan Server using @EnableInfinispanRemoteHttpSession, enabling session sharing across application instances.

Prerequisites

  • Java 17+

  • Spring Boot

  • An Infinispan Server running on localhost:11222

Step 1: Add Dependencies

Add the Infinispan Spring Boot remote starter, Spring Web, Thymeleaf, and Spring Session:

<dependency>
   <groupId>org.infinispan</groupId>
   <artifactId>infinispan-spring-boot4-starter-remote</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.session</groupId>
   <artifactId>spring-session-core</artifactId>
</dependency>

Step 2: Enable Remote HTTP Sessions

Annotate your main application class with @EnableInfinispanRemoteHttpSession:

@SpringBootApplication
@EnableInfinispanRemoteHttpSession
public class UserSessionsApp {

    public static void main(String... args) {
        new SpringApplicationBuilder().sources(UserSessionsApp.class).run(args);
    }
}

Step 3: Configure the Sessions Cache

Use an InfinispanRemoteCacheCustomizer to configure the "sessions" cache with Protobuf marshalling:

@Configuration
public class InfinispanConfiguration {

   @Bean
   @Order(Ordered.HIGHEST_PRECEDENCE)
   public InfinispanRemoteCacheCustomizer caches() {
      return b -> {
         // Ask the server to create this cache on startup
         URI uri;
         try {
           uri = this.getClass().getClassLoader().getResource("sessionsCacheConfig.xml").toURI();
         } catch (URISyntaxException e) {
            throw new RuntimeException(e);
         }

         b.remoteCache("sessions").configurationURI(uri);
         // Use protostream marshaller to serialize the sessions with Protobuf
         b.remoteCache("sessions").marshaller(ProtoStreamMarshaller.class);
      };
   }
}

Step 4: Use Session Attributes in a Controller

Store and retrieve data from the HTTP session as usual:

@Controller
@SessionAttributes("greetings")
public class WebController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name,
                           Model model, HttpSession session) {
        model.addAttribute("name", name);
        model.addAttribute("latest", session.getAttribute("latest"));
        session.setAttribute("latest", name);
        return "greeting";
    }

}

Step 5: Run the Tutorial

mvn spring-boot:run

Visit http://localhost:8080/greeting?name=Katia. Refresh the page to see the previous name persisted in the session. Sessions are stored in the remote Infinispan Server, so they survive application restarts.

What’s Next