redis管理分布式session


ngnix:一個高性能的HTTP反向代理服務器,用來分發請求

一.安裝ngnix

  1. http://nginx.org/en/download.html 下載,本人安裝的windows版本(1.12.2),安裝成功之后可直接啟動;
  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;
        #    }
        #}
    
    }
    ngnix.conf

 

二.配置兩個端口不同的tomcat,測試ngnix

  1. 一個配置為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;
    }
View Code

  如圖使用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.confg
    • 重啟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丟失需要重新登陸;

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM