专栏首页九州牧云Externalizing Session State for a Spring Boot Application Using Spring-Session

Externalizing Session State for a Spring Boot Application Using Spring-Session

Spring-session is a very cool new project that aims to provide a simpler way of managing sessions in Java based web applications. One of the features that I explored with spring-session recently was the way it supports externalizing session state without needing to fiddle with the internals of specific web containers like Tomcat or Jetty.

To test spring-session I have used a shopping cart type application(available here) which makes heavy use of session by keeping the items added to the cart as a session attribute, as can be seen from these screenshots:

Consider first a scenario without Spring session. So this is how I have exposed my application:

I am using nginx to load balance across two instances of this application. This set-up is very easy to run using Spring boot, I brought up two instances of the app up using two different server ports, this way:

mvn spring-boot:run -Dserver.port=8080
mvn spring-boot:run -Dserver.port=8082

and this is my nginx.conf to load balance across these two instances:

events {
    worker_connections  1024;
}
http {
    upstream sessionApp {
        server localhost:8080;
        server localhost:8082;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://sessionApp;
        }       
    }
}

I display the port number of the application in the footer just to show which instance is handling the request.

If I were to do nothing to move the state of the session out the application then the behavior of the application would be erratic as the session established on one instance of the application would not be recognized by the other instance - specifically if Tomcat receives a session id it does not recognize then the behavior is to create a new session.

Introducing Spring session into the application

There are container specific ways to introduce a external session stores - One example is here, where Redis is configured as a store for Tomcat. Pivotal Gemfire provides a module to externalize Tomcat's session state.

The advantage of using Spring-session is that there is no dependence on the container at all - maintaining session state becomes an application concern. The instructions on configuring an application to use Spring session is detailed very well at the Spring-session site, just to quickly summarize how I have configured my Spring Boot application, these are first the dependencies that I have pulled in:

<dependency>
 <groupId>org.springframework.session</groupId>
 <artifactId>spring-session</artifactId>
 <version>1.0.0.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
 <groupId>org.springframework.session</groupId>
 <artifactId>spring-session-data-redis</artifactId>
 <version>1.0.0.BUILD-SNAPSHOT</version>
</dependency>
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-redis</artifactId>
 <version>1.4.1.RELEASE</version>
</dependency>
<dependency>
 <groupId>redis.clients</groupId>
 <artifactId>jedis</artifactId>
 <version>2.4.1</version>
</dependency>

and my configuration to use Spring-session for session support, note the Spring Boot specific FilterRegistrationBean which is used to register the session repository filter:

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.web.filter.DelegatingFilterProxy;

import java.util.Arrays;

@Configuration
@EnableRedisHttpSession
public class SessionRepositoryConfig {

 @Bean
 @Order(value = 0)
 public FilterRegistrationBean sessionRepositoryFilterRegistration(SessionRepositoryFilter springSessionRepositoryFilter) {
  FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  filterRegistrationBean.setFilter(new DelegatingFilterProxy(springSessionRepositoryFilter));
  filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
  return filterRegistrationBean;
 }

 @Bean
 public JedisConnectionFactory connectionFactory() {
  return new JedisConnectionFactory();
 }
}

And that is it! magically now all session is handled by Spring-session, and neatly externalized to Redis.

If I were to retry my previous configuration of using nginx to load balance two different Spring-Boot applications using the common Redis store, the application just works irrespective of the instance handling the request. I look forward to further enhancements to this excellent new project.

The sample application which makes use of Spring-session is available here: https://github.com/bijukunjummen/shopping-cart-cf-app.git。

Reference:

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Redis ZSET

    For the past 2 years I’ve been all about Redis, and something I’m continually ex...

    九州暮云
  • 发生java.lang.OutOfMemoryError: Direct buffer memory 转

    下面是在掉坑了,出现了一次 java.lang.OutOfMemoryError: Direct buffer memory 错误后的总结。

    九州暮云
  • BlackHole开发日记-一次压力测试及JVM调优的经过

    BlackHole开发很久了,目前稳定性、性能都还可以了,但是作为一个Java程序,内存开销一直是硬伤,动不动100M内存下去了,对于单机用户实在是不太友好。

    九州暮云
  • linux kernel Documentation filesystems overlayfs

    Please see MAINTAINERS file for where to send questions.

    heidsoft
  • 使用Authorization scope对SAP CRM附件模型进行权限控制

    The attachment authorization control could be implemented with the help of autho...

    Jerry Wang
  • 相机标定--A Flexible New Technique for Camera Calibration

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.n...

    用户1148525
  • 在Mac下刻录光盘

    在Mac下如何刻录光盘呢,在Spotlight中搜索了dvd、cd什么的,出来的程序基本上都不能刻录光盘,一时摸不着头脑。查了资料之后,才发现Mac的光盘刻录在...

    大江小浪
  • PAT 1007

    Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is...

    week
  • Mock 不是 Stub

    中英文对照:https://github.com/smilingsun/blog/issues/9

    前端博客 : alili.tech
  • 一种新的高光谱卫星图像分类空间光谱框架(CS)

    高光谱卫星图像目前被广泛用于准确的灾害预测和地形特征分类。然而,在这样的分类任务中,目前的大多数方法只使用到图像中包含的光谱信息。 因此,在本文中,我们提出了一...

    太子钟

扫码关注云+社区

领取腾讯云代金券