java web项目,不依赖于web容器,实现负载均衡,必须解决session共享问题。
spring-session +redis是最方面快捷的,不用重复造轮子,且不用修改项目的代码,并且使项目使用的session与web容器解耦,
完全由容器的httpsession转为使用spring提供的session.
具体怎么使用,请访问spring的官方网站。
项目中使用spring session+redis的步骤。
项目使用的是maven结构的web项目
- pom.xm
<!-- 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>
<!-- 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>
系统中的代码一点也不用改动真的解耦啊,spring非常强大!