前言
本章学习Nginx配置负载均衡时所需要注意的Session共享问题
方法
1.概念
我们知道,Nginx做负载均衡的时候需要两个或多个Tomcat的支持。由于每个tomcat都有访问的机会,那么Session共享的问题就比较突出了,最直观的感受就是用户的登录信息一般都保存在session中,一旦刷新网页切换tomcat,结果可想而知!!
为了避免上面问题的发生,我们将讨论有关Session共享的问题。
2.详细操作步骤
1)准备工作
本次除了需要Nginx和两个Tomcat外,还需要Redis作为Session共享的关键。
2)引入相关jar
本次我所使用的构建工具是Gradle,所以一下的配置都来自Gradle,Maven也是类似的。
compile "redis.clients:jedis:2.9.0"
compile "org.springframework.data:spring-data-redis:1.8.20.RELEASE"
compile "org.springframework.session:spring-session:1.3.5.RELEASE"
我这里的配置是这样的,博友们可根据需要进行版本的选择,注意不要冲突。
注意:这里需要Redis的相关jar包。
3)配置项目的web.xml和spring配置文件applicationContext.xml
web.xml加入如下代码:
<filter>
<filter-name>springSessionRepositoryFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSessionRepositoryFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
applicationContext.xml加入如下代码:
下面有一部分是配置Redis的ip和端口号,请根据需要进行相关配置。
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="127.0.0.1"/>
<property name="port" value="6379"/>
<property name="database" value="0"/>
</bean>
注意:运行项目时要保证你的Redis服务处于开启状态。
到这里Session就配置完了,是不是很简单。