java web项目,不依赖于web容器,实现负载均衡,必须解决session共享问题。网上解决方法有很多,但是我觉得使用

spring-session +redis是最方面快捷的,不用重复造轮子,且不用修改项目的代码,并且使项目使用的session与web容器解耦,

完全由容器的httpsession转为使用spring提供的session.

具体怎么使用,请访问spring的官方网站 <http://projects.spring.io/spring-session/>。

这里写下我的项目中使用spring session+redis的步骤。

项目使用的是maven结构的web项目

1.pom.xml
<!-- spring-session begin--> <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId> <version>1.7.6.RELEASE</version>
</dependency> <dependency> <groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId> <version>1.3.0.RELEASE</version>
</dependency> <dependency> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <version>2.8.1</version> </dependency>
<dependency> <groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId> <version>2.4.2</version>
<scope>compile</scope> </dependency> <!-- spring-session end-->

注意:刚开始我的spring框架包(就是好多spring的包)用的是4.0的,但是启动tomcat服务器的时候报错,说不能初始化redisTemplate,跑去stackofflow上看,有说是因为jar的问题,需要升级spring框架必须高于4.2.1,因为redistemplate换了构造器。于是将spring框架升到4.3.7.RELEASE。就ok了。

2.配置filter

在web.xml中,加上这段配置 必须位于filter链的最前面
<!-- spring-session --> <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> <dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher> </filter-mapping>
3.在applicationContext.xml(这是我的spring容器配置文件的名字)中注册需要的bean。(用注解也行,但我是用的xml配置)
<!-- redis --> <bean id="jedisPoolConfig"
class="redis.clients.jedis.JedisPoolConfig"> </bean> <bean
id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost" /> <property name="port"
value="6379" /> <property name="password" value="****"/> <property
name="usePool" value="true"/> <property name="poolConfig"
ref="jedisPoolConfig"/> </bean> <bean id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"> <property
name="connectionFactory" ref="jedisConnectionFactory"/> </bean> <!--
将session放入redis --> <bean id="redisHttpSessionConfiguration"
class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="1800"/> </bean>
OK,到这儿就结束了,系统中的代码一点也不用改动。这真的解耦啊,spring这的非常强大!

感兴趣的朋友可以关注微信公众号(会定时推送新的知识):


友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信