Session using Redis storage nginx Tomcat Load Balancer cluster

Source: Internet
Author: User
Tags redis port number tomcat tomcat server nginx reverse proxy

Environment: Cent OS 7.0 (Virtual machine Environment), Nginx 1.9.8, Redis 3.2.1 One, background

When using NGINX+TOMCAT to achieve load balancing, because nginx to different requests distributed to a certain tomcat,tomcat at the time of operation is different containers, because the session will be out of sync or missing issues. second, nginx installation and configuration

1, Nginx Installation

Online resources for the installation of Nginx more, for example, the simplest is:

(1) Get Nginx, on the http://nginx.org/download/to get the latest version of the current download, for example:

wget http://nginx.org/download/nginx-1.9.8.tar.gz


(2) Unzip the TAR-XVF nginx-1.9.8.tar.gz package.

(3) Enter the unzip directory and execute the./configure--prefix=/usr/local/nginx-1.9.8 install nginx into the/usr/local/nginx-1.9.8 directory

(4) Make & Make Install

The installation process will install Nginx into the/usr/local/nginx-1.9.8 directory, start the Nginx test can start normally.

2, modify NGINX configuration multi-Tomcat server

2.1, modify the conf/nginx.conf file, add upstream on the top of the server tag as follows:

Upstream Mynginxserver {
    #weigth参数表示权值, the higher the weight, the greater the chance of being allocated
    #本机上的Squid开启3128端口
        server 127.0.0.1:8080 weight=1 ;
        Server 127.0.0.1:8060 weight=1;
    }

Here specify the native two tomcat instances, the port is 8080,8060, the weight is 1, behind the configuration Tomcat instance, mynginxserver this is their own arbitrary name, the bottom to use

2.2, configure the server tag;

server {
        listen       ;
        server_name  192.168.1.149;

        #charset Koi8-r;

        #access_log  logs/host.access.log  main;

        Location/{
           # root   html;
           # index  index.html index.htm;
           Proxy_pass http:
        }


        error_page   502 503 504  /50x.html;
        Location =/50x.html {
            root   html;
        }

2.3, the complete content after the configuration is as follows (1.9.8 version deleted the comments after the configuration content):

Worker_processes  1;

Events {
    worker_connections  ;
}

HTTP {
    include       mime.types;
    Default_type  Application/octet-stream;

    Sendfile on        ;

    Keepalive_timeout  ;

    Upstream Mynginxserver {
        server 127.0.0.1:8080 weight=1;
        Server 127.0.0.1:8060 weight=1;
    }

    server {
        listen       ;
        server_name  192.168.1.149;

        Location/{
           proxy_pass http://mynginxserver; 
        }

        Error_page   502 503 504  /50x.html;
        Location =/50x.html {
            root   html;}}
}

2.4, specific configuration items and the specific meaning of the configuration items, please refer to
https://www.nginx.com/resources/wiki/start/topics/examples/full/ Three, Tomcat multi-instance configuration

1, decompression apache-tomcat-7.0.67.zip get apache-tomcat-7.0.67

[Root@localhost www]

2. Rename the apache-tomcat-7.0.67 to TOMCAT1

[Root@localhost www]

Repeat the 1, 2 process to get TOMCAT1 and Tomcat2 as follows:

3. Modify the port of TOMCAT1 to 8080 and deploy the project file

Edit the Conf/server.xml under Tomcat, modify the port number to 8080,

Write your own Web Project war package for testing Nginx reverse proxy download Address: http://download.csdn.net/detail/u010870518/9585683

After downloading, put the extracted project files into the tomcat1/webapps/root/directory:

Modify the index.jsp and login.jsp files to identify each Tomcat container as specific

4. Modify the port of Tomcat2 to 8060 and deploy the project file

Edit the Conf/server.xml under Tomcat, modify the port number to 8060, and then, as in the 3 above, download the war content and place it under tomcat2/webapps/root/. Modify index.jsp and login.jsp to identify the specific Tomcat container

5. Start TOMCAT1 and TOMCAT2 respectively

6. Restart Nginx Service, Access IP address: 192.168.1.149:80 (this is the virtual machine IP address of the access)

7. Viewing effect

As can be seen, Nginx has been requested to distribute, forwarded to a specific Tomcat four, the installation and configuration of Redis

Because the length is too long, please refer to I write: http://blog.csdn.net/xlgen157387/article/details/52022793 five, Tomcat-redis-session-manager use of open source projects

1. Open Source Project address: Https://github.com/jcoleman/tomcat-redis-session-manager

2. After downloading the code, you need to recompile, generate the required jar, create any MAVEN project, and copy the code under SRC to the exact location, as follows:

MAVEN's pom.xml files are as follows:


    4.0.0

    com.ufind.session
    tomcat-redis-session
    1.0-snapshot

    
        
            org.apache.tomcat
            Tomcat-catalina
            7.0.27
        
        
            redis.clients
            jedis
            2.7.2
        
    

    
        
            
                org.apache.maven.plugins
                Maven-compiler-plugin
                3.0
                
                    1.7
                    1.7
                    UTF-8
                
            
        
    

3. Then open terminal, execute MVN clean and mvn install to package the compiled code as: Tomcat-redis-session-1.0-snapshot.jar

4, will Tomcat-redis-session-1.0-snapshot.jar, Jedis-2.7.2.jar, Commons-pool2-2.0.jar Three jar packages are placed in the Lib directory under the TOMCAT1 and Tomcat2 instances, respectively.

Free download of these three jar:http://download.csdn.net/detail/u010870518/9585716

5. Modify the Conf/contex.xml file under Tomcat instance

  
  
    Web-inf/web.xml  

      
      
          

  

If Redis is configured with access rights, add the password as:

  
  
    Web-inf/web.xml  

      
      
          

  

If you do not set the password will error, as follows:

vi. demonstration of effect

A login request for a case demonstration, after the successful login, the user information is placed in the session, displayed in the interface (TOMCAT1 instance, tomcat2 instance only in the H2 tag to do the logo)

1. login.jsp File:

Session Demo in Tomcat1User name: Password:

2, index.jsp will be logged in the information displayed on the interface


Session Demo in Tomcat1<% User user = (user) request.getsession (). getattribute (); if (user = = null) {%> user is empty, no login ... <%} else {%> welcome: <%=user.getusername ()%> <%}%>

3. servlet Processing Request Code

public class Userservlet extends Baseservlet {public

    String login (httpservletrequest request, HttpServletResponse Response)
            throws Servletexception, IOException {

        User user = new User ();
        User.setusername (Request.getparameter ());
        User.setuserpassword (Request.getparameter ());
        Request.getsession (). SetAttribute (, user);

        return;
    }

}

4, the effect is as follows:

Can be seen in the login interface when the request to refresh Tomcat has been distributed by Nginx request, after logging in two tomcta have shared the session

5. View Redis's memory for session

When configuring the Contex.xml file, the default database is 0, and the REDIS-CLI tool can be used to see

Vii. Summary

Tomcat-redis-session-manager is a fully transparent user of the distributed session storage framework, the user only need to make a simple configuration in Tomcat, it can be used, our business code is completely and single instance of the code is the same, That is, when you write code, you don't have to worry about writing a multi-tomcat instance of code that is completely transparent.

How to understand the principle of the framework, we first need to know that in the request process session, the first to parse the SessionID information in the request, and then store the SessionID into the request's parameter list. Then, when the session is retrieved from request, if there is a SessionID then the session is taken from the session pool based on the ID, if the SessionID does not exist or the session fails, Then the session is created and the session information is placed in the session pool for the next use.

If we want to write ourselves a project similar to Tomcat-redis-session-manager, we should know the session management mechanism of Tomcat, in the case of the default Tomcat session management, If it is not set up, it is controlled by the Standardmanager class that the tomcat comes with, and we can customize a manager based on this class. The main rewrite is the org.apache.catalina.session.ManagerBase inside the specific write operation,
This is also the basic principle of tomcat-redis-session-manager, which points the session storage location of Tomcat to Redis

Redissessionmanager inherited Org.apache.catalina.session.ManagerBase and re-wrote the Add, Findsession, Createemptysession, remove and other methods, and add and delete the session to the operation of the Redis data store is pointed to the operation

Interested to refer to a session in Tomcat management mechanism: http://www.cnblogs.com/interdrp/p/4935614.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.