Nginx integrates the tomcat cluster and shares sessions ---- test case, nginxtomcat

Source: Internet
Author: User

Nginx integrates the tomcat cluster and shares sessions ---- test case, nginxtomcat

Recently, out of curiosity, I have studied tomcat cluster configuration and integrated nginx to achieve load balancing, session sharing, and write records to prevent forgetting. --------- Self-cultivation of chicken dishes.

 

Note: The blogger uses A web project to deploy it under two tomcat servers at the same time (tomcat-A, ingress A-B) and uses nginx as A reverse proxy Based on the configured weights, distribute requests to tomcatA/tomcatB in the background and share sessions.

Configure the Local Domain Name Pointing to: Modify the host file: Add 127.0.0.1 www.domain.com.cn

Create a project: tiny-demo-operation. Use springmvc to configure the springmvc. xml configuration file.

Create SessionShareSetController and SessionShareGetController

The directory is as follows:

SessionShareSetController code:

1 package com. tiny. session. share. controller; 2 3 import javax. servlet. http. httpServletRequest; 4 import javax. servlet. http. httpServletResponse; 5 import javax. servlet. http. httpSession; 6 7 import org. springframework. stereotype. controller; 8 import org. springframework. web. bind. annotation. requestMapping; 9 10 @ Controller11 @ RequestMapping ("/sessionShare") 12 public class SessionShareSetController {13 14 @ RequestMapping ("/sessionSet") 15 public String sessionSet (HttpServletRequest request, 16 HttpServletResponse response) throws Exception {17 18 HttpSession session = request. getSession (); 19 String name = "tinyseven-demo-operation" + "---"; 20 String remote = request. getRemoteHost () + "---" 21 + request. getRemoteAddr () + "---" + request. getRemotePort () 22 + "---"; 23 String local = request. getLocalName () + "---" + request. getLocalAddr () 24 + "---" + request. getLocalPort () + "---"; 25 String server = request. getServerName () + "---" 26 + request. getServerPort () + "---"; 27 request. setAttribute ("name", name); 28 request. setAttribute ("remote", remote); 29 request. setAttribute ("local", local); 30 request. setAttribute ("server", server); 31 32 session. setAttribute ("name", name); 33 return "sessionshare/sessionSet"; 34} 35 36}View Code

SessionShareGetController code:

1 package com. tiny. session. share. controller; 2 3 import javax. servlet. http. httpServletRequest; 4 5 import org. springframework. stereotype. controller; 6 import org. springframework. web. bind. annotation. requestMapping; 7 8 @ Controller 9 @ RequestMapping ("/sessionShare") 10 public class SessionShareGetController {11 12 @ RequestMapping ("/sessionGet") 13 public String sessionGet (HttpServletRequest request) throws Exception {14 15 String name = (String) request. getSession (). getAttribute ("name") 16 + "---"; 17 String remote = request. getRemoteHost () + "---" 18 + request. getRemoteAddr () + "---" + request. getRemotePort () 19 + "---"; 20 String local = request. getLocalName () + "---" + request. getLocalAddr () 21 + "---" + request. getLocalPort () + "---"; 22 String server = request. getServerName () + "---" 23 + request. getServerPort () + "---"; 24 request. setAttribute ("name", name); 25 request. setAttribute ("remote", remote); 26 request. setAttribute ("local", local); 27 request. setAttribute ("server", server); 28 return "sessionshare/sessionGet"; 29 30} 31}View Code

Create a jsp page:

The directory is as follows:

SessionSet. jsp code:

<Body> current user sets session -- server -- >$ {server} </br> current user sets session -- remote -- >$ {remote} </br> current user settings session -- local -- >$ {local} </br> the current user sets session -- name -- >>> {name} </br> </body>View Code

SessionGet. jsp code:

1 <body> 2 server requested by the current user >>$ {server} </br> 3 remote requested by the current user >>$ {remote} </br> 4 Current user requested local >>> {local} </br> 5 name of the current user request >>> {name} </br> 6 </body>View Code

 

 

1. Prepare two tomcat servers and create a tomcat cluster.

The blogger uses apache-tomcat-6.0.37

Path: E: \ Server \ apache-tomcat-6.0.37-node-A

E: \ Server \ apache-tomcat-6.0.37-node-B

Modify server. xml of A/B separately to ensure that the two tomcat servers can be started properly, avoid port conflicts, and create two tomcat clusters.

1. modify server of. xml, add 1 before all ports, for example, (<Server port = "8005" shutdown = "SHUTDOWN"> change to <Server port = "18005" shutdown = "SHUTDOWN"> other similar)

Modify <Engine name = "Catalina" defaultHost = "localhost"> to <Engine name = "Catalina" defaultHost = "localhost" jvmRoute = "tomcat1">

 

2. modify server of B. xml, add 2 before all ports, for example, (<Server port = "8005" shutdown = "SHUTDOWN"> change to <Server port = "28005" shutdown = "SHUTDOWN"> other similar)

Modify <Engine name = "Catalina" defaultHost = "localhost"> to <Engine name = "Catalina" defaultHost = "localhost" jvmRoute = "tomcat2">

At this time, both tomcat servers can be started successfully.

 

3. Create two tomcat cluster services.

Cancel the/B server. xml files

<! --
<Cluster className = "org. apache. catalina. ha. tcp. SimpleTcpCluster"/>
-->

.

Restart tomcat A and tomcat B (startup. bat in the running bin) and find that the following information is more than the previous one, indicating that the two tomcat nodes have been associated.

2. Release the project to tomcatA and tomcatB, and configure session sharing.

1. Modify the server. xml file of tomcaA and tomcatB.

<Host name = "localhost" appBase = "webapps"
UnpackWARs = "true" autoDeploy = "true"
XmlValidation = "false" xmlNamespaceAware = "false">

<! -- 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 -->
<! --
<Valve className = "org. apache. catalina. valves. AccessLogValve" directory = "logs"
Prefix = "localhost_access_log." suffix = ". txt" pattern = "common" resolveHosts = "false"/>
-->
<Context docBase = "E: \ javaWorkspace \ tiny-demo-operation \ WebRoot "reloadable =" true "path ="/tiny-demo-operation "crossContext =" true "source =" org. eclipse. jst. jee. server: tiny-demo-operation "/> add content here

</Host>

2. Modify the web. xml file of the published Project

Before the web. xml file </web-app>, add

<! -- Session sharing configuration -->
<Distributable/>

 

At this time, the current project can achieve session sharing in two tomcat servers. The effect is as follows:

Access the project under tomcatA and set the session:

Access the project under tomcatB and obtain the session:

3. Integrate nginx for request distribution. Nginx1.5.0 is used here.

1. After nginx. conf is modified

1 # users and groups used by Nginx; 2 # user niumd is not specified in the window; 3 # Number of sub-processes (usually equal to or twice as high as the CPU) 4 5 worker_processes 2; 6 7 # error log storage path 8 # error_log logs/error. log; 9 # error_log logs/error. log notice; 10 11 error_log logs/error. log info; 12 13 # specify the pid to store the file 14 15 pid logs/nginx. pid; 16 17 events {18 # epoll is recommended for linux using the network I/O model. kqueue is recommended for FreeBSD and is not specified for Windows. 19 # use epoll; 20 # maximum number of connections allowed 21 worker_connections 2048; 22} 23 24 http {25 26 include mime. types; 27 default_type application/octet-stream; 28 # define the log format 29 # log_format main '$ remote_addr-$ remote_user [$ time_local] $ request '30 #' "$ status" $ body_bytes_sent "$ http_referer" '31 #'" $ http_user_agent "" $ http_x_forwarded_for "'; 32 # access_log off; 33 access_log logs/access. log; 34 client_header_timeout 3 m; 35 clie Nt_body_timeout 3 m; 36 send_timeout 3 m; 37 bytes 1 k; 38 bytes 4 4 k; 39 sendfile on; 40 tcp_nopush on; 41 tcp_nodelay on; 42 # keepalive_timeout 75 20; 43 include gzip. conf; 44 include proxy. conf; 45 46 upstream localhost {47 # allocate requests to backend tomcat Based on ip computing. Many people mistakenly believe that session problems can be solved, but they cannot. 48 # When the same machine is deployed on multiple networks, the ip address may be different. 49 # ip_hash; 50 # The weigth parameter indicates the weight, the higher the weight, the higher the probability of being allocated to 51 server localhost: 18080 weight = 5; 52 server localhost: 28080 weight = 5; 53 54} 55 56 server {57 58 listen 80; 59 server_name localhost; 60 61 location/{62 root E:/javaWorkspace/tiny-demo-operation/WebRoot; 63 index index.html index.htm; 64 65} 66 67 location ~ \. (Html | js | css | png | gif) ${68 root E:/javaWorkspace/tiny-demo-operation/WebRoot; 69} 70 71 location ~ \. (Jsp | action) ${72 proxy_connect_timeout 3; 73 proxy_send_timeout 30; 74 proxy_read_timeout 30; 75 proxy_pass http: // localhost; 76} 77} 78}View Code

2. Restart nginx

To access the current project under the VM, nginx automatically distributes requests. The results are as follows:

Distribute to tiny-demo-operation under tomcatB and set the attribute value name in the session.

 

Distribute tiny-demo-operation in tomcatA to obtain the attribute value name in the session.

 

 

So far, we have implemented a simple test case of integrating nginx with tomcat clusters to achieve load balancing and 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.