Quantcast
Channel: Active questions tagged redis+java - Stack Overflow
Viewing all articles
Browse latest Browse all 2204

Integrating Redis for Session Management in Spring MVC Application?

$
0
0

I have a Spring MVC application currently deployed on Tomcat 9, and I'm looking to enhance its session management by integrating Redis. The application currently uses Spring Session with Tomcat's default session management, but we want to switch to Redis for better scalability and persistence.

Here's an overview of our current setup and the changes we're aiming to implement:

Current Setup:

<!-- Dependencies for Spring Session with Redis --><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-core</artifactId><version>2.7.4</version></dependency><dependency><groupId>org.springframework.session</groupId><artifactId>spring-session-data-redis</artifactId><version>2.7.4</version></dependency><dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId><version>6.3.1.RELEASE</version></dependency>

Objective:

Implement Redis-based session management in the Spring MVC application.Ensure scalability and persistence of session data using Redis.What I've Done So Far:

Added necessary dependencies for Spring Session with Redis (using Lettuce as the Redis client).Configured Spring Session to use Redis for session management.

Problem Encountered:

While I've made progress in configuring Redis for session management, I'm encountering issues with setting up the session ID resolver and configuring the Redis connection properly. When I check redis data using redis-cli I can session being created. I'm unsure if my current configuration is correct or if there are additional steps I need to take to ensure everything works smoothly.

Code Snippet:

@PropertySource(value = "file:${APP_CONFIG}/redis.properties", ignoreResourceNotFound = false)@EnableRedisHttpSession(redisNamespace = "spring:session:demo", cleanupCron = "0 */5 * * * ?", flushMode = FlushMode.IMMEDIATE, saveMode = SaveMode.ALWAYS)@Order(Ordered.HIGHEST_PRECEDENCE)public class SessionConfig extends AbstractHttpSessionApplicationInitializer {    @Value("${redis.port}")    private Integer redisPort;    @Value("${redis.host}")    private String redisHost;    @Value("${redis.pass}")    private String redisPassword;    private static final Logger log = LoggerFactory.getLogger(SessionConfig.class);    @Bean    @Primary    public LettuceConnectionFactory redisConnectionFactory() {        log.error("Creating LettuceConnectionFactory with Redis host: {} and port: {}", redisHost, redisPort);        final RedisStandaloneConfiguration redisStandaloneConfig = new RedisStandaloneConfiguration();        redisStandaloneConfig.setHostName(redisHost);        redisStandaloneConfig.setPort(redisPort);        redisStandaloneConfig.setPassword(redisPassword);        final LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfig);        // lettuceConnectionFactory.setValidateConnection(true);        lettuceConnectionFactory.setEagerInitialization(true);        lettuceConnectionFactory.afterPropertiesSet();        return lettuceConnectionFactory;    }    @Bean    @Order(Ordered.HIGHEST_PRECEDENCE)    public HttpSessionIdResolver httpSessionIdResolver() {        CookieHttpSessionIdResolver resolver = new CookieHttpSessionIdResolver();        DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();        cookieSerializer.setCookieName("JSESSIONID"); //        cookieSerializer.setCookiePath("/");        cookieSerializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");        cookieSerializer.setUseBase64Encoding(true);        resolver.setCookieSerializer(cookieSerializer);        return resolver;    }}

Observations:

Multiple JSESSIONID Values: Upon loading the login page in the browser, I notice two JSESSIONID values being generated. One appears to be created by Redis, while the other seems to be associated with Tomcat's session management mechanism.

Consistency in Redis Session ID: Upon successful authentication, I've verified that the session ID retrieved from Redis matches the one stored in the database.

Inconsistent Session Retrieval: In certain sections of my code, when attempting to access the session using RequestContextHolder, I'm obtaining the Tomcat session ID (JSESSIONID value), rather than the one managed by Redis.

In below code, I get the Redis-generated session ID:

    @Override    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {        HttpSession session = request.getSession(true);//other codes    }

While in below, I get the Tomcat session JSESSIONID:

ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpSession session = requestAttributes.getRequest().getSession();

Viewing all articles
Browse latest Browse all 2204

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>