spring整合redis

這裏有一篇文章介紹很詳細,我參考他的
需要的jar包文件如下
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>
接着在spring配置文件中引入redis配置

最後在web.xml中引用redis保存session配置


這樣整合就完成了
當然如果想實現session共享,nginx負載均衡,在程序保存用戶session時要改變一下保存方式,應該保存到session中
user中包含用戶登陸信息
request.getSession().setAttribute("user", JSON.toJSON(user));
//原有保存是這樣的session.setAttribute("user", u);,但這樣只能存在與當前服務器的session中
清除用戶登陸信息
request.getSession().removeAttribute("user");
這樣就把redis加入到spring中,後面配置nginx負載均衡,就不會出現請求轉發後用戶登陸數據消失不同步的現象
nginx環境搭建,我會在下面筆記中整理
發佈了54 篇原創文章 · 獲贊 28 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章