Mongo-backed sessions¶
The spring-session-data-mongodb module stores sessions in MongoDB through the reactive Mongo driver — a natural choice when your application already uses Spring Data Mongo.
Step 1: add the dependencies¶
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-mongodb</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-reactivestreams</artifactId>
</dependency>
Step 2: configure the Mongo connection¶
@Configuration
public class MongoConfig extends AbstractReactiveMongoConfiguration {
@Value("${mongo.uri}")
String mongoUri;
@Override
public MongoClient reactiveMongoClient() {
return MongoClients.create(mongoUri);
}
@Override
protected String getDatabaseName() {
return "blog";
}
}
With the connection property set in application.properties:
Start a MongoDB server for local development:
Step 3: enable Mongo web session¶
@EnableMongoWebSession registers a reactive session repository backed by MongoDB automatically. The controller and template code is identical to the in-memory example.
Verify¶
Start the application, submit the attribute form at http://localhost:8080, and inspect the blog database — the sessions live in a dedicated collection with the attributes and a TTL index for expiry.
You can explore the complete codes in spring-reactive-sample/session-data-mongo.