Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this article, we’ll learn how to combine Spring Session with Spring WebFlux. Specifically, we’ll learn how to use Spring WebSession, which unites Spring Session with Spring Boot 2’s WebFlux.

A Spring Session is defined as “a simplified Map of name-value pairs”. Sessions track values that are important to an HTTP session, like Users and Principals. Thus, we can use Session management along with the new reactive WebFlux Mono and Flux objectsSpring Session also supports using different application containers (rather than only Tomcat).

For more about Spring Session, check out another great article here on Baeldung.

2. Maven Setup

Now, let’s get our app set up and configured. Thankfully, configuring our pom.xml is pretty easy to do. First, we need to use Spring Boot 3.x.x along with the relevant Spring Session dependencies. Add the newest version through Maven Repository:

Then, we add them to pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.1.5</version>
</dependency>
<dependency> 
    <groupId>org.springframework.session</groupId> 
    <artifactId>spring-session-core</artifactId> 
    <version>3.1.5</version> 
</dependency>

Those two dependencies are the minimum requirements for in-memory Session management.  For Redis, use:

Then, add the following to the pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>3.1.5</version>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
    <version>3.1.5</version>
 </dependency>

Now, let’s configure our classes.

3. In-Memory Configuration

To use in-memory configuration, add the config class:

@Configuration
@EnableSpringWebSession
public class SessionConfig {
 
    @Bean
    public ReactiveSessionRepository reactiveSessionRepository() {
        return new ReactiveMapSessionRepository(new ConcurrentHashMap<>());
    }
}

That associates a (reactive) repository with your session manager. It’ll store those values in a HashMap.

Importantly, the configuration class must include the @EnableSpringWebSession annotation.

4. Redis Configuration

Now, let’s hook up Redis. To use Redis to manage WebSessions, add the configuration class:

@Configuration
@EnableRedisWebSession
public class RedisConfig {
 
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }
}

Note that the configuration class must include the @EnableRedisWebSession annotationRemember, we can’t use the@EnableRedisWebSession and EnableSpringWebSession annotations together without causing an exception.

Docker is one of the easiest ways to interact with Redis. After installing Docker, we only need to enter three commands to do so. Run the command to bring up a Redis instance:

$ docker stop redis
$ docker rm redis
$ docker run -d --name redis -p 6379:6379 redis:4.0.5-alpine

Next, let’s test our app.

5. In Practice

Now, let’s add a reactive REST controller to our app:

@GetMapping("/websession")
public Mono getSession(WebSession session) {

    session.getAttributes().putIfAbsent("id", 0);
    session.getAttributes().putIfAbsent("note", "Howdy Cosmic Spheroid!");

    CustomResponse r = new CustomResponse();
    r.setId((int) session.getAttributes().get("id"));
    r.setNote((String) session.getAttributes().get("note"));

    return Mono.just(r);
}

Then, we can use WebSession by adding a parameter to our REST handlers:

@GetMapping("/websession/test")
public Mono<CustomResponse> testWebSessionByParam(@RequestParam(value = "id") int id,
  @RequestParam(value = "note") String note, WebSession session) {

    session.getAttributes().put("id", id);
    session.getAttributes().put("note", note);

    CustomResponse r = new CustomResponse();
    r.setId((int) session.getAttributes().get("id"));
    r.setNote((String) session.getAttributes().get("note"));

    return Mono.just(r);
}

We can get or set values using the .getAttributes() method, which returns a Map.

Let’s spin up our Spring app:

websession one

After the server is up and running, we can change the default WebSession values (0  and “Howdy Cosmic Spheroid!”). Run cURL command:

$ curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X GET http://localhost:8080/websession/test?id=222&note=helloworld

or visit the URL http://localhost:8080/websession/test?id=222&note=helloworld. Thereafter, the  JSON returned from localhost:8080/websession will display updated Session values:

websession three

That endpoint, localhost:8080/websession, returns the current WebSession attributes id and note.

6. Conclusion

We’ve learned how to add Spring WebSession to our WebFlux applications. For more information, check out the great official documentation.

As always, the code samples used in this article are available on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.