这篇文章大致讲解了用Nginx+Tomcat+Spring+Redis实现分布式session。
Spring项目地址:https://github.com/hshenCode/spring_redis_exercise
1. 系统拓扑
- 1台Redis服务器,用来存储session。
- 2台Tomcat服务器,访问Redis进行session存储。
- 1台Nginx服务器,作为反向代理以及负载均衡器,把请求转发到Tomcat服务器上
- 用户直接访问Nginx服务器
2. Nginx作为反向代理
由于Nginx的多进程模式以及事件驱动, 它作为一个web服务器的性能是相当好的。 至于怎么用它来做反向代理,只需要很简单的配置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;
}
}
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