DEV Community

Raja Anbazhagan
Raja Anbazhagan

Posted on • Updated on

Store spring sessions in Separate Database

Storing session details in Redis or database is usually a good idea. However,
the default implementation of spring-session-jdbc uses the primary data source to store and
retrieve data from the session related tables. This can be a problem when there is a large amount of session related
operations to the database.

The solution here is to define a custom datasource bean and mark it with @SpringSessionDataSource as shown below.

@Bean
@SpringSessionDataSource
public DataSource sessionDataSource() {
    return sessionDataSource();
}
Enter fullscreen mode Exit fullscreen mode

However, when you define multiple data sources, you end up breaking the default auto-configurations involving the primary data source.

To avoid all that, you need to mark one datasource as primary and somehow create and feed the second datasource to the session auto-configuration.

Follow this post about Store spring sessions in Separate Database to learn how and why you should do it this way.

Top comments (0)