ngnix+ Tomcat +memcached cluster set server load balancing, session sharing

Source: Internet
Author: User
Tags session id server port tomcat server

1. Preparatory work:

Download nginx-1.8.0 website:http://nginx.org/

TOMCAT7 Two, apache-tomcat-7.0.62 version, I named TOMCAT1,TOMCAT2

Memcache Service: Memcached.exe,

1.1 Load Balancing configuration

1.1.1 Configuration Nginx


#user nobody;worker_processes 2; #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 localhost {#根据ip计算将请求分配各那个后端tomcat, many people mistakenly think that can solve the session problem, in fact, can not.         #同一机器在多网情况下, routing switching, IP may be different #ip_hash;        Server localhost:8080 weight=5;      Server localhost:8088 weight=5;        } server {Listen 80;        server_name localhost;        #charset Koi8-r;        #access_log Logs/host.access.log Main; LocatiOn/{Proxy_connect_timeout 3;  Proxy_send_timeout 30;  Proxy_read_timeout 30;        Proxy_pass http://localhost;        } #error_page 404/404.html;        # REDIRECT Server error pages to the static page/50x.html # Error_page 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$ {# ProX        Y_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 # #l Ocation ~/\.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; #    }    #}}



Change the place:


upstream localhost {
#根据ip计算将请求分配各那个后端tomcat, many people mistakenly think that can solve the session problem, in fact, can not.
#同一机器在多网情况下, routing switching, IP may be different
#ip_hash;
server localhost:8080 weight=5;
server localhost:8088 weight=5;
}

Location /{
proxy_connect_timeout 3;
Proxy_send_timeout 30;
Proxy_read_timeout 30;
proxy_pass http://localhost;
}

1.1.2tomcat Configuration


To balance two tomcat, you need to modify some ports, one by default, one Tomcat to the other (instead of the default port value of +1).

There are three port modifications:

1) <server port= "8006" shutdown= "Shutdown" >

2) <connector port= "8081" protocol= "http/1.1" connectiontimeout= "20000" redirectport= "8443"/&G T

3) <connector port= "8010" protocol= "ajp/1.3" redirectport= "8443"/>

There is also a place where two tomcat needs to be changed: Add a Jvmroute attribute on the engine, requiring two tomcat values to be different

<engine name= "Catalina" defaulthost= "localhost" jvmroute= "Tomcat1" >

My complete Tomcat server.xml file


<?xml version= ' 1.0 ' encoding= ' utf-8 '?><!--Licensed to the Apache software Foundation (ASF) under one or more C  Ontributor license agreements.  See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");  You are not a use of this file except in compliance with the License.  Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable or agreed to writing, software distributed under the License are distributed on a "as is" BASIS, without warranties  or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions and limitations under the license.--><!--note:a     ' Server ' is not itself a ' Container ', so that you are not define subcomponents such as ' valves ' at the this level. Documentation At/docs/config/server.html--&GT; <server port= "8005" shutdown= "shutdown" > <listener classname= " Org.apache.catalina.startup.VersionLoggerListener "/> <!--Security Listener. Documentation at/docs/config/listeners.html <listener classname= "Org.apache.catalina.security.SecurityListener "/>-<!--APR Library loader. Documentation At/docs/apr.html--<listener classname= "Org.apache.catalina.core.AprLifecycleListener" Sslengine= "on"/> <!--Initialize Jasper prior to WebApps is loaded. Documentation At/docs/jasper-howto.html--<listener classname= "Org.apache.catalina.core.JasperListener"/ > <!--Prevent memory leaks due to use of particular Java/javax apis--> <listener classname= "Org.apache.cata Lina.core.JreMemoryLeakPreventionListener "/> <listener classname=" Org.apache.catalina.mbeans.GlobalResourcesLifecycleListener "/> <listener classname=" Org.apache.catalina.core.ThreadLocalLeakPreventionListener "/> <!--Global JNDI ResourCes documentation at/docs/jndi-resources-howto.html-<GlobalNamingResources> <!--Editable user Database that can also is used by Userdatabaserealm to authenticate users--<resource name= "Userdat Abase "auth=" Container "type=" Org.apache.catalina.UserDatabase "description=" User database that Can be updated and saved "factory=" org.apache.catalina.users.MemoryUserDatabaseFactory "pathname = "Conf/tomcat-users.xml"/> </GlobalNamingResources> <!--a "Service" is a collection of one or more "Connec Tors "that share a single" Container "Note:a" Service "was not itself a" Container ", so if not define Su       Bcomponents such as "valves" at the This level. Documentation at/docs/config/service.html-<service name= "Catalina" > <!--the connectors can use a sh Ared executor, you can define one or more named thread pools--> <!--<executor naMe= "Tomcatthreadpool" nameprefix= "catalina-exec-" maxthreads= "4" minsparethreads=--<!--A "Connector" represents an endpoint by which requests is received and responses are returned. Documentation At:java HTTP Connector:/docs/config/http.html (Blocking & non-blocking) Java AJP Con  Nector:/docs/config/ajp.html APR (HTTP/AJP) Connector:/docs/apr.html Define a Non-ssl http/1.1 Connector               On port 8080--<connector port= "8080" protocol= "http/1.1" connectiontimeout= "20000" redirectport= "8443"/> <!--A "Connector" using the shared thread pool--> <!--<connector exe               Cutor= "Tomcatthreadpool" port= "8080" protocol= "http/1.1" connectiontimeout= "20000"  redirectport= "8443"/>-<!--Define a SSL http/1.1 Connector on port 8443 this Connector uses The BIO implementation that requires the JSSE style configuration. When using the apr/native implementation, the OpenSSL style configuration is required as described in the Apr/nati                ve documentation-<!--<connector port= "8443" protocol= "Org.apache.coyote.http11.Http11Protocol" Maxthreads= "sslenabled=" true "scheme=" "https" secure= "true" Clientauth= "false" Sslprotoco L= "TLS"/>-<!--Define an AJP 1.3 Connector on port 8009-<connector port= "8009" protocol= "         ajp/1.3 "redirectport=" 8443 "/> <!--an Engine represents the entry point (within Catalina) that processes  Every request. The Engine implementation for Tomcat stand alone analyzes the HTTP headers included with the request, and passes T         Hem on to the appropriate host (virtual host).     Documentation At/docs/config/engine.html-<!--should set Jvmroute to support load-balancing via AJP ie: <engine name= "Catalina" defaulthost= "localhost" jvmroute= "jvm1" >-<engine name= "Catalina" defaulthost= "localhost" jvmroute= "tomcat > <!--for clustering, click a look at documentation at:/docs/cluster-howto.html o)/docs/config/cluster.html (reference documentation)-<!--<cluster Classname= "Org.apache . catalina.ha.tcp.SimpleTcpCluster "/>-<!--use the Lockoutrealm-prevent attempts to guess user pa        Sswords via a brute-force attack-<realm classname= "Org.apache.catalina.realm.LockOutRealm" > <!--This Realm uses the userdatabase configured in the global JNDI resources under the key "Userdatab  ASE ". Any edits that is performed against this userdatabase is immediately available for use by the Re  Alm. --<realm classname= "Org.apache.catalina.realm.UserDatabaseRealm" resourcename= "userdatabase"/ > </realm>  

Test Load: Change two tomcat WebApp directory root of the index.jsp file, just make a mark, the page output TOMCAT1,TOMCAT2 respectively,

Start Ngnix, TOMCAT1,TOMCAT2 service, enter localhost/index.jsp on the address bar, refresh several times will appear

Description The load succeeded through the Ngnix.


The previous session ID is the same, because I have done the session copy function,

The session replication feature is simple to configure:

The required jar package,

Asm-3.2.jar,kryo-1.04.jar,kryo-serializers-0.10.jar,memcached-session-manager-1.6.3.jar,minlog-1.2.jar,msm-javolution-ser Ializer-1.6.3.jar,msm-kryo-serializer-1.6.3.jar,msm-xstream-serializer-1.6.3.jar,reflectasm-0.9.jar,spymemcached-2.8.4.ja R,memcached-session-manager-tc7-1.6.5.jar this jar package into Tomcat lib.

Tomcat6 used by Memcached-session-manager-tc6-1.6.3.jar, mine is tomcat7 used to be Memcached-session-manager-tc7-1.6.5.jar file Http://pan.baidu.com/s/1hqxYXyG

Replace the corresponding version of the jar yourself

Two tomcat inside the context.xml join

<manager classname= "De.javakaffee.web.msm.MemcachedBackupSessionManager"        memcachednodes= "M1 : 127.0.0.1:11211 "        sticky=" false "        lockingmode=" Auto "        sessionbackupasync=" false "        sessionbackuptimeout= "transcoderfactoryclass="        De.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory "  />



tomcat/webapp/root/index.jsp page
<%@ page contenttype= "text/html; Charset=utf-8 "%> <%@ page import=" java.util.* "%> 

is the load map above,

Remove the context.xml inside the tomcat.

<manager classname= "De.javakaffee.web.msm.MemcachedBackupSessionManager"
Memcachednodes= "m1:127.0.0.1:11211"
Sticky= "false"
Lockingmode= "Auto"
Sessionbackupasync= "false"
sessionbackuptimeout= "1000"
transcoderfactoryclass= "De.javakaffee.web.msm.serializer.kryo.KryoTranscoderFactory"/>


This shows that the session is not shared.




ngnix+ Tomcat +memcached cluster set server load balancing, session sharing

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.