第一种方式:通过redis共享
1.pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
2.添加redis地址,这里用了集群,单机也可以
spring.redis.cluster.nodes=192.168.220.136:7001,192.168.220.136:7002,192.168.220.136:7003,192.168.220.135:7004,192.168.220.135:7005,192.168.220.135:7006
3.在启动类上添加@EnableRedisHttpSession注解
@EnableRedisHttpSession
public class SpringBootRedisApplication extends SpringBootServletInitializer
页面访问my.test.com时两台服务器129和133的切换效果
查看redis情况
7001上存储的是session过期时间,还有1582秒
7003上存储的是session主体,有sessionid,创建时间等
本次用到的服务器
1. 1台Nginx 192.168.220.100
upstream redis_site{
server 192.168.220.129:8081 weight=1;
server 192.168.220.133:8080 weight=2;
}
server {
listen 80;
server_name localhost;
server_name my.test.com;
location =/{
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://redis_site/index;
}
location ~/{
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://redis_site;
}
}
2. 2台redis组成的集群 192.168.220.136;192.168.220.135
3.2台tomcat服务器192.168.220.129:8081;192.168.220.133:8080
后续几种实现方式:
- Tomcat通过session复制的方式
- Nginx通过IP-HASH方式
- memcached的MSM(Memcached_Session_Manager)方案
- 还有通过数据库表存储session的方式