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 principal name of the authenticated users is stored as an NCache Tag.
Prerequisites
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<!--for NCache Enterprise-->
<artifactId>ncache-spring-sessions</artifactId>
<version>x.x.x</version>
</dependency>
- Import the following packages in your Java client application:
- The cache must be running.
- Make sure that the data being added is serializable.
- 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.
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 configurations@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: demoCachenamespace -> default: "spring:sessions:"maxInactiveInterval -> default: 1000 secondssaveMode -> default: ON_SAVEflushMode -> 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