标签:
1.准备工作:
下载nginx-1.8.0 网址:http://nginx.org/
tomcat7两个,apache-tomcat-7.0.62版本的,我命名为tomcat1,tomcat2
memcache服务: memcached.exe,
1.1 负载均衡配置
1.1.1 配置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,许多人误认为可以解决session问题,其实并不能。 #同一机器在多网情况下,路由切换,ip可能不同 #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 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; # } #} }
upstream localhost {
#根据ip计算将请求分配各那个后端tomcat,许多人误认为可以解决session问题,其实并不能。
#同一机器在多网情况下,路由切换,ip可能不同
#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 配置
要均衡两个tomcat,需要修改一些端口,一个默认,一个tomcat修改成其它端口(改为在默认端口值+1)。
有三处端口修改:
1)<Server port="8006" shutdown="SHUTDOWN">
2) <Connector port="8081" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
3)<Connector port="8010" protocol="AJP/1.3" redirectPort="8443" />
还有一处是两个tomcat都需要改的地方:在Engine上添加个jvmRoute属性,要求两个tomcat的值都不一样
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat1">
本人完整的tomcat server.xml文件
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor 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 may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "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 you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/server.html --> <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 are 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.catalina.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 be used by UserDatabaseRealm to authenticate users --> <Resource name="UserDatabase" 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 "Connectors" that share a single "Container" Note: A "Service" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/service.html --> <Service name="Catalina"> <!--The connectors can use a shared executor, you can define one or more named thread pools--> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <!-- A "Connector" represents an endpoint by which requests are received and responses are returned. Documentation at : Java HTTP Connector: /docs/config/http.html (blocking & non-blocking) Java AJP Connector: /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 executor="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/native documentation --> <!-- <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" maxThreads="150" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="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 them on to the appropriate Host (virtual host). Documentation at /docs/config/engine.html --> <!-- You 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, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) --> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <!-- Use the LockOutRealm to prevent attempts to guess user passwords 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 "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> <Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log." suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> </Host> </Engine> </Service> </Server>
测试负载:更改两个tomcat的webapp目录下ROOT的index.jsp文件,只是做个标记,页面分别输出tomcat1,tomcat2,
启动ngnix ,tomcat1,tomcat2服务,在地址栏上输入localhost/index.jsp,刷新几次则会出现
说明通过ngnix负载成功了.
上面的SESSION ID相同,是因为我已做好了session复制功能了,
session复制功能配置能简单:
需要的jar包,
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-serializer-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.jar,memcached-session-manager-tc7-1.6.5.jar将这个jar包放到tomcat lib里.
tomcat6使用的memcached-session-manager-tc6-1.6.3.jar,我的是tomcat7使用的是memcached-session-manager-tc7-1.6.5.jar 文件下载地址http://pan.baidu.com/s/1hqxYXyG
自行更换对应版本的jar
两个tomcat里面的context.xml加入
<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" />
<%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="java.util.*" %> <html><head><title>Cluster Test</title></head> <body> <% //HttpSession session = request.getSession(true); System.out.println(session.getId()); out.println("<br> SESSION ID:" + session.getId()+"<br>"); // 如果有新的请求,则添加session属性 String name = request.getParameter("name"); if (name != null && name.length() > 0) { String value = request.getParameter("value"); session.setAttribute(name, value); } out.print("<b>Session List:</b>"); Enumeration<String> names = session.getAttributeNames(); while (names.hasMoreElements()) { String sname = names.nextElement(); String value = session.getAttribute(sname).toString(); out.println( sname + " = " + value+"<br>"); System.out.println( sname + " = " + value); } %> <h2>tomcat1</h2> </body> </html>
效果图就是上面的负载图,
去掉tomcat下context.xml里面的
<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" />
效果图:
由此可见session不是共享的.
ngnix+ tomcat +memcached 集群设置服务器负载均衡,session共享
标签:
原文地址:http://my.oschina.net/stonezing/blog/499919