Using Spring Sessions
This section will guide you through integrating NCache into your Spring Boot applications for efficient and scalable Spring session management.These sessions can be regular or indexed. For indexed Spring sessions the prinicipal name of the authenticated users is stored as a NCache Tag.
Prerequisites to Use Spring Sessions
- To learn about the supported Java versions, please refer to the NCache Installation Guide.
- The Spring Framework version should be 6.0.12 or higher.
Add Maven Packages
You must add the following in your pom.xml
file while working with the NCache Spring Sessions integration.
<!-- NCache Spring Session Integration -->
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-spring-session</artifactId>
<version>x.x.x</version>
</dependency>
Spring Sessions Implementation
You will have to add an annotation to your application to connect spring sessions with NCache. To do so, add the following to the class with the main function:
@SpringBootApplication // this is needed so that spring can read the user created Beans and Configurations
Further, you will also have to add one of the following to add configurations:
@EnableNCacheHttpSession // uses the default configutaions
@EnableNCacheHttpSession(cacheName = "demoCache")
However, if you want to add indexed sessions, you must use the @EnableNCacheIndexedHttpSession
which can be defined using the configurations mentioned above.
If you require custom settings you will have to pass arguments in the annotation. These custom settings are separated by a comma like cacheName="demoCache", namespace="randomNamespace"
and can include the following:
cacheName -> default: demoCache
namespace -> default: "spring:sessions:"
maxInactiveInterval -> default: 1000 seconds
saveMode -> default: ON_SAVE
flushMode -> default: ON_SAVE
For example, if we had a guessing game that used sessions we would employ annotations as follows:
package com.alachisoft.ncache.guessgame;
import com.alachisoft.ncache.spring.sessions.config.annotation.web.http.EnableNCacheHttpSession;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
/*
annotation to get access to NCache for session storage. Pass arguments in the annotation if you want custom settings. You can pass:
1) cacheName -> default: demoCache
2) namespace -> default: "spring:sessions:"
3) maxInactiveInterval -> default: 1000 seconds
4) saveMode -> default: ON_SAVE
5) flushMode -> default: ON_SAVE
*/
@EnableNCacheHttpSession(cacheName = "spring")
public class GuessGameApplication {
public static void main(String[] args) {
SpringApplication.run(GuessGameApplication.class, args);
}
}
See Also
Configure Application for Generic Spring Caching Provider
NCache as Spring Data Cache