redis管理分布式session
ngnix:一个高性能的HTTP和反向代理服务器,用来分发请求
一.安装ngnix
- http://nginx.org/en/download.html 下载,本人安装的windows版本(1.12.2),安装成功之后可直接启动;
- 修改配置文件nginx.conf,upstream中可配置多个tomcat,我使用的一台电脑将两个tomcat端口修改不同,location中将root,index注释,新增proxy_pass http://myTomcat;重启ngnix: nginx -s reload
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 0; #keepalive_timeout 65; #gzip on; upstream myTomcat{ #这里指定多个源服务器,ip:端口,80端口的话可写可不写 server 127.0.0.1:801 weight=1; server 127.0.0.1:802 weight=1; #ip_hash; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #server_name localhost; location / { #root html; #index index.html index.htm; proxy_pass http://myTomcat; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} }
二.配置两个端口不同的tomcat,测试ngnix
- 一个配置为801,一个配置为802;修改tomcat server.xml
2.修改tomcat首页,方便来测试ngnix是否分发请求;
3.启动两个tomcat,浏览器访问localhost; ngnix默认是轮询的方式;浏览器访问localhost
上图分别为第一/二次访问localhost,第一次访问的是801,第二次访问的是802
三.代码
简单的编写一下controller代码; 两个页面,一个登陆页面,一个购买页面;
public Map<String,String> login(String userName, String pass, HttpSession session){ Map<String,String> userMap = new HashMap<String, String>(); userMap.put("userName",userName); userMap.put("pass",pass); session.setAttribute("userInfo",userMap); Map<String,String> resultMap = new HashMap<String, String>(); resultMap.put("flag","1"); return resultMap; } public Map<String,String> buy(HttpSession session){ Map<String,String> resultMap = new HashMap<String, String>(); resultMap.put("flag","1"); try { Map<String,String> userInfo = (Map<String,String>)session.getAttribute("userInfo"); userInfo.get("userName"); userInfo.get("pass"); }catch (Exception e){ resultMap.put("flag","0"); } return resultMap; }
如图使用maven将项目打包放到tomcat/webapps下
启动tomcat访问localhost/项目名/登陆页面,输入账户密码登陆,在购买页面点击购买,发现第一次购买成功,第二次需要重新登陆;即第二次请求的服务器已经与第一次不同了;
四.解决分布式session的方案
4.1.ngnix配置ip_hash,使某个ip的请求固定访问某一台服务器; 在upstream节点中增加ip_hash;
-
- 配置文件如下
-
upstream myTomcat{ #这里指定多个源服务器,ip:端口,80端口的话可写可不写 server 127.0.0.1:801 weight=1; server 127.0.0.1:802 weight=1; ip_hash; }
- 重启ngnix,进行三中的操作发现多次购买都可以成功; 优点:配置快捷;缺点:如果一台服务器宕机那么该服务器对应的ip都不能正常使用;
4.2.tomcat session复制,这个没有测试,网上找的一篇 https://www.cnblogs.com/hanxianlong/p/3456780.html;
优点:正好弥补第一个的缺点,其中一个服务器宕机不影响 缺点:资源占用浪费
4.3.利用spring session+redis解决共享Session问题
4.3.1.在pom文件中引入spring session的相关依赖
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>1.1.1.RELEASE</version> <type>pom</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.5.RELEASE</version> </dependency> </dependencies>
4.3.2.在web.xml的配置文件中加载spring-session的配置文件,比如spring-session.xml。
<filter> <filter-name>springSessionRepositoryFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSessionRepositoryFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这个filter的配置应该在web工程的其他filter配置之前。这个filter的配置应该在web工程的其他filter配置之前。
<param-value>classpath:spring-servlet.xml,classpath:customer.xml</param-value>
4.3.3.在spring-session.xml的配置文件中配置相关的信息。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <!--springSession 配置--> <bean id="sessionConfiguration" class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> <!--修改session的有效时间--> <property name="maxInactiveIntervalInSeconds" value="1800"></property> </bean> <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="xxx.xx.xxx.xx"></property> <property name="port" value="6379"></property> </bean> </beans>
4.3.4 测试
代码不用修改,无缝插入,再次打war包放到tomcat下; 可以多次购买;同时查看redis会发现多了一些数据,session信息在里面存放
执行 hget spring:session:sessions:e70c182c-2ddc-4085-abbc-a1107cf0186c sessionAttr:userInfo 如下
如果将该key-value删除则再次点击购买则session丢失需要重新登陆;