我在分布式session上的一些實踐_架構

來源:互聯網
上載者:User

這篇文章大致講解了用Nginx+Tomcat+Spring+Redis實現分布式session。

Spring項目地址:https://github.com/hshenCode/spring_redis_exercise


1. 系統拓撲


1台Redis伺服器,用來儲存session。 2台Tomcat伺服器,訪問Redis進行session儲存。 1台Nginx伺服器,作為反向 Proxy以及負載平衡器,把請求轉寄到Tomcat伺服器上 使用者直接存取Nginx伺服器


2. Nginx作為反向 Proxy
由於Nginx的多進程模式以及事件驅動, 它作為一個web伺服器的效能是相當好的。 至於怎麼用它來做反向 Proxy,只需要很簡單的配置nginx.conf檔案的以下部分並且重啟Nginx即可:

    upstream web_app{        server      ip1:port;        server      ip2:port;    }    server {        listen       80;        server_name  localhost;             location / {            proxy_pass      http://web_app;            proxy_set_header        X-Real-IP       $remote_addr;        }    }

這裡的ip1, ip2以及port就是你的兩台tomcat的地址。

3.使用Redis儲存Session
Tomcat預設會把session儲存在記憶體中,一方面限制了最大session數量,另一方面又阻礙了做分布式拓展。 一個解決方案就是用Redis或者別的資料庫來持久化session。 在SpringMVC中的實現就很簡單了,只要在spring設定檔中配置以下的bean即可:
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <property name="maxTotal" value="${redis.maxTotal}"/>        <property name="maxIdle" value="${redis.maxIdle}"/>        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>    </bean>    <bean id="jedisConnectionFactory"          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <property name="hostName" value="${redis.host}"/>        <property name="port" value="${redis.port}"/>        <property name="timeout" value="${redis.timeout}"/>        <property name="poolConfig" ref="jedisPoolConfig"/>    </bean>    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">        <property name="connectionFactory" ref="jedisConnectionFactory"/>    </bean>
    <bean id="redisHttpSessionConfiguration"          class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">        <property name="maxInactiveIntervalInSeconds" value="1800"/>    </bean>

這個配置是什麼意思呢。
首先前3個bean配置了對redis的串連和訪問,我們可以在代碼中直接用redisTemplate去操作Redis。 最後一個bean的作用是配置web 容器(在這裡是tomcat)對Session的管理方法。
至於Tomcat是如何管理Session的,可以參考這篇文章:  http://www.cnblogs.com/interdrp/p/4935614.html



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.