This article roughly explains the implementation of distributed session with Nginx+tomcat+spring+redis.
Spring Project Address: https://github.com/hshenCode/spring_redis_exercise
1. System topology
1 Redis servers to store sessions. 2 tomcat servers, accessing Redis for session storage. 1 nginx servers, as reverse proxies and load balancers, forward requests to the Tomcat server for direct access to the Nginx server
2. Nginx as reverse proxy
Because of the nginx and event-driven, the performance of a Web server is quite good. As for how to use it as a reverse proxy, only a very simple configuration of the following parts of the nginx.conf file and restart Nginx can be:
Upstream web_app{
server ip1:port;
Server ip2:port;
}
server {
listen ;
server_name localhost;
Location/{
proxy_pass Http://web_app;
Proxy_set_header x-real-ip $remote _addr
}
}
Here's ip1, IP2 and Port are your two Tomcat addresses.
3. Use Redis to store session
Tomcat stores the session in memory by default, limiting the maximum number of sessions on the one hand and hindering distributed expansion on the other. One solution is to use Redis or other databases to persist sessions. The implementation in SPRINGMVC is simple, as long as the following beans are configured in the Spring configuration file:
<bean id= "Jedispoolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property name= "Maxtotal" "Value=" ${redis.maxtotal} "/> <property name=" Maxidle "value=" ${redis.maxidle} "/> <property na Me= "Maxwaitmillis" value= "${redis.maxwaitmillis}"/> <property name= "Testonborrow" value= W} "/> </bean> <bean id=" jedisconnectionfactory "class=" Org.springframework.data.redis.conne Ction.jedis.JedisConnectionFactory "> <property name=" hostName "value=" ${redis.host} "/> <proper Ty name= "Port" value= "${redis.port}"/> <property name= "Timeout" value= "${redis.timeout}"/> <PR Operty name= "Poolconfig" ref= "Jedispoolconfig"/> </bean> <bean id= "redistemplate" class= "ORG.SPRINGFR" Amework.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>
What does this configuration mean?
First 3 beans are configured to connect and access Redis, and we can use Redistemplate to manipulate Redis in our code. The last bean's role is to configure the Web container (here is Tomcat) for the session management method.
As for how Tomcat manages the session, refer to this article: http://www.cnblogs.com/interdrp/p/4935614.html