Centos 7 (3) configure the Tomcat Cluster

Source: Internet
Author: User
Tags dateformat


A cluster is a collection of multiple servers to provide external interface access, which is completely transparent to users. A common method is to put a server on the front end and distribute user requests to different servers, there are roughly the following solutions:
1) DNS round robin: Resolve the user's connection to different servers. This will cause a problem. If a server goes down and the DNS cannot be updated in time, problems will occur.
2) reverse proxy server: it forwards user connections to different servers. There are two ways to do this: Modify the HTTP header and redirect user connections to a fixed server, it will not interact with the proxy server in the future. This will modify the address in the user's browser and may be unfriendly. if the address is not modified, the proxy server may become a bottleneck if the user is always transferred through the proxy server.
3) the MAC address is forwarded. All Server IP addresses are the same and direct to different machines through devices.
For proxy problems, session sharing may occur. One way is to fix a specific user on a server so that session sharing does not exist. This method is the simplest, however, the algorithm efficiency is very important and needs to be selected by yourself. There is also the sharing of sessions on all servers, such as in databases, shared directories, or memcached. However, these implementation methods have certain problems, for example, the stored data needs to be serialized, and the shared server will become a weak point in the system. In addition, the session should be copied to keep the same session information for all servers. In this case, if too many servers are required, will seriously affect the performance.
System Configuration
Centos 7, 192.168.1.14, Apache 80, nginx 808, tomcat8 8081, tomcat8 8082

Optional
1) nginx: Fixed server access. This is very simple. Modify nginx. conf and use the ip_hash Command, as shown below:
HTTP {
.............
Upstream tomcat_server_pool {
Ip_hash;
Server 192.168.1.14: 8081 Weight = 4 max_fails = 2 fail_timeout = 30 s;
Server 192.168.1.14: 8082 Weight = 4 max_fails = 2 fail_timeout = 30 s;
}
Server {
Listen 808;
SERVER_NAME localhost;

Charset UTF-8;

# Access_log logs/host. Access. Log main;

If (-d $ request_filename)
{
Rewrite ^/(. *) ([^/]) http: // $ host/$1 $2/permanent;
}
Location /{
# Root HTML;
Index index.html index.htm index. Do;

Proxy_next_upstream http_502 http_504 error timeout invalid_header;
Proxy_pass http: // tomcat_server_pool;
# Proxy_set_header host www.shiyq.com;
Proxy_set_header X-forwarded-for $ remote_addr;
}

We can see that nginx forwards port 808 to port 8081/8082 of the Local Machine and creates a spring MVC project. The virtual directory is study. Modify the default file as follows:
Homecontroller. Java, add the following content
@ Requestmapping (value = "/index. Do", method = requestmethod. Get)
Public String home_do (locale, model, httpservletrequest request ){
Logger.info ("Welcome home! The client locale is {}. ", locale );

Date = new date ();
Dateformat = dateformat. getdatetimeinstance (dateformat. Long, dateformat. Long );

String formatteddate = dateformat. Format (date );

String host_str = ", the host is" + request. getlocaladdr () + ":" + request. getlocalport ();
Httpsession session = request. getsession ();

String check = request. getparameter ("check ");
If (check! = NULL &&! Check. Equals ("")){
Session. setattribute ("name", "Shi Yongqiang ");
}

Logger.info ("the name in session is {}", (string) Session. getattribute (" name "));
String test_str = (string) Session. getattribute ("host_str ");


Model. addattribute ("servertime", formatteddate + ", the host is" + host_str );

Model. addattribute ("name", session. getattribute ("name "));

Model. addattrid ("sessionid", session. GETID ());

Return "home ";
}
Modify home. jsp as follows:
<% @ Taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "C" %>
<% @ Page session = "false" %>
<HTML>
<Head>
<Title> Home </title>
</Head>
<Body>
<H1>
Hello world!
</H1>

<P> the time on the server is $ {servertime}. </P>
<P> the name in session is $ {name}. </P>
<P> the session ID is $ {sessionid}. </P>
</Body>
</Html>
Sometimes garbled characters may occur. Modify the following content:
Add the following in Web. xml:
<Filter>
<Filter-Name> encoding </filter-Name>
<Filter-class> org. springframework. Web. Filter. characterencodingfilter </filter-class>
<Init-param>
<Param-Name> encoding </param-Name>
<Param-value> UTF-8 </param-value>
</Init-param>
<Init-param>
<Param-Name> forceencoding </param-Name>
<Param-value> true </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-Name> encoding </filter-Name>
<URL-pattern>/* </url-pattern>
</Filter-mapping>

The above configuration is suitable for solving the problem of method = post. If the get method is required to support Chinese characters, for example, form is submitted in get mode, or click the link to support Chinese characters, modify CONF/server in the Tomcat root directory. in the XML file, find <connector Port = "8080"/> and add <connector Port = "8080" uriencoding = "UTF-8"/>
Note that if it is used for development server, you need to find the correct location, such as the configuration file under the eclipse servers.
However, you cannot enter Chinese characters in the address bar.
In this situation, access http: // 192.168.1.14: 808/study/index. do? Check = 1
The output is
Hello world!
The time on the server is August 6, 2014 11:39:48 A.M., the host is, the host is 192.168.1.14: 8081.

The name in session is Shi Yongqiang.

The session ID is c318a769671490e6822c047524990000f.
After refresh, you can see that a fixed server is accessed, which ensures that the user session will not go wrong.
2) use memcache
This requires the nginx session plug-in and the Tomcat memcache plug-in, but code.google.com cannot be accessed. Although there are many documents, it cannot be implemented. Let's take a look at it later.
Only session replication is allowed.
3) Tomcat 8 is very simple to configure the cluster. Of course, this cluster method replicates sessions through broadcast. When the number of sessions reaches a certain level, it will inevitably cause a broadcast storm and is not suitable for large systems.
The simplest setting method is as follows:
A) Remove the <cluster> label comment in server. xml. The default value is as follows:
<Cluster classname = "org. Apache. Catalina. Ha. tcp. simpletcpcluster"/>
B) add a line to Web. XML in the Web-app where the session needs to be copied: <distributable/>
C) disable the firewall: Service iptables stop. If firewalld is used, run the service firewalld Stop command.
Notes for setting up a cluster (Official Document)
A) All session attributes must implement java. Io. serializable.
B) Remove the comment on the cluster element in server. xml.
C) if you want to customize valves, make sure to set replicationvalve
D) Make sure that <distributable/> is added to Web. xml.
E) If mod_jk is used, set the jvmroute attribute in the engine to be consistent with the worker name of workers. properties.
F) Ensure that all the time is the same and the time is synchronized through the NTP server.
G) Make sure that your server Load balancer is set to session stick mode (sticky session mode)
Access http: // 192.168.1.104: 808/study/index in the browser. do, you will find that when ip_hash is set, according to the prompts on the page, you will find that you always access a server, turn off the tomcat, And then refresh the page, you will find that you will automatically access another tomcat, the session information remains unchanged.
If the ip_hash mode is removed, nginx automatically accesses the system in sequence, but its session ID remains unchanged.
For better testing, visit http: // 192.168.1.14: 8081/study/index. do and http: // 192.168.1.14: 8082/study/index. do, you will find a consistent session ID, and you can also access http: // 192.168.1.14: 8081/study/index. do? Check = 1. At this time, the attribute value of the session has been set, and then access http: // 192.168.1.14: 8082/study/index. Do To know that session replication has occurred.
If you need more complex customization effects, you can refer to the document
You can add the following rules for firewall problems:
Iptables-A input-I eth0-D 224.0.0.4-J accept
Vim/etc/sysconfig/iptables
Add the following content:
-A input-p udp-M state -- state new-m udp -- dport 45564-J accept
Start Firewall
Service iptables save
Service iptables start
3) Apache + mod_jk + Tomcat Solution
A) download the Apache Development Kit
Yum install httpd -*
B) download mod_jk
Wget http://mirrors.cnnic.cn/apache/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.40-src.tar.gz
Tar xvf tomcat-connectors-1.2.40-src.tar.gz
CD tomcat-connectors-1.2.40-src.tar.gz
CD native
./Configure -- With-apxs =/bin/apxs
Make
Make install
C) Configure Apache
Because httpd. conf contains files in the conf. Module. d directory, create 00-add.conf in this directory and enter the following content:

Loadmodule jk_module modules/mod_jk.so # load the module
Jkworkersfile CONF/worker. properties # load the mod_jk configuration file

Jkmount/* worker3 # Forward the root directory to worker3, which is a server Load balancer server that contains two Apache servers.

<Ifmodule dir_module>
Directoryindex index. jsp index. Do
</Ifmodule>
D) Create the workder. properties file in the conf directory. The content is as follows:
Worker. List = worker3
Worker. worker1.type = ajp13
Worker. worker1.host = localhost
Worker. worker1.port = 8009
Worker. worker1.lbfactor = 1
Worker. worker1.connection _ pool_time out = 600
Worker. worker1.socket _ keepalive = 1
Worker. worker1.socket _ timeout = 60

Worker. worker2.type = ajp13
Worker. worker2.host = localhost
Worker. worker2.port = 8010
Worker. worker2.lbfactor = 1
Worker. worker2.connection _ pool_time out = 600
Worker. worker2.socket _ keepalive = 1
Worker. worker2.socket _ timeout = 60

Worker. worker3.type = LB
Worker. worker3.balance _ workers = worker1, worker2
It can be seen that worker1 corresponds to the port 8009 of the local machine, that is, the configured tomcat8-1, worker2 corresponds to the port 8010 of the local machine, that is, the configured tomcat8-2 server, worker3 stands for the load balancing server, includes two members worker1 and worker2.
E) Configure Tomcat
Vim/work/tomcat8-1/CONF/server. xml
Modify the following content and add jvmroute = "worker1" to the engine label"
<Engine name = "Catalina" defaulthost = "localhost" jvmroute = "worker1">
Vim/work/tomcat8-2/CONF/server. xml
Modify the following content and add jvmroute = "worker2" to the engine label"
<Engine name = "Catalina" defaulthost = "localhost" jvmroute = "worker2">
F) Restart Apache and tomcat. Enter http: // 192.168.1.14/study/index. Do in the browser to view similar content.
The time on the server is August 6, 2014 05:21:04 P.M., the host is, the host is 192.168.1.14: 80.

The name in session is.

The session ID is ae132d73152e74c043ed64ed6f27707e. worker2.
Here is an interesting thing. The session ID will add an I Extension, namely worker1 or workder2, which should be the role of jvmroute, but in essence it is still a session.
One problem with mod_jk is that I don't know which machine to access. Because the Apache address port is displayed, I can use session to know which machine it is.
We have configured nginx Server Load balancer before. Enter http: // 192.168.1.14: 808/study/index. Do in the browser.
The session ID is indeed the same with the suffix removed, and run http: // 192.168.1.14: 808/study/index. do? Check = 1. The session information is shared.

In general, it is much easier to configure Server Load balancer with nginx, mod_jk is much more troublesome, and tomcat session replication is also very easy, but remember to configure the firewall. If there is a problem, it is possible to turn off the firewall immediately.

 

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.