commons-pool2-2.2.jar
jedis-2.7.3.jar
spring-data-redis-1.6.1.RELEASE.jar
spring-session-1.1.1.RELEASE.jar
spring-session-data-redis-1.0.2.RELEASE.jar
首先创建配置文件
redis.properties
#注意不要有空格
再创建spring-redis.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- session设置 -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="3600"></property>
</bean>
<!-- redis连接池 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
<!-- redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<!-- <property name="password" value="${redis.password}"/> -->
<property name="timeout" value="${redis.timeout}"/>
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- session设置 -->
<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
<property name="maxInactiveIntervalInSeconds" value="3600"></property>
</bean>
<!-- redis连接池 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"/>
<!-- redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<!-- <property name="password" value="${redis.password}"/> -->
<property name="timeout" value="${redis.timeout}"/>
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
</bean>
</beans>
接着在spring配置文件中引入redis配置
最后在web.xml中引用redis保存session配置
这样整合就完成了
当然如果想实现session共享,nginx负载均衡,在程序保存用户session时要改变一下保存方式,应该保存到session中
user中包含用户登陆信息
//原有保存是这样的session.setAttribute("user", u);,但这样只能存在与当前服务器的session中
清除用户登陆信息
这样就把redis加入到spring中,后面配置nginx负载均衡,就不会出现请求转发后用户登陆数据消失不同步的现象
nginx环境搭建,我会在下面笔记中整理