這篇文章大致講解了用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