Table of Contents
Nginx Load scheduler dual Tomcat load and session replication MySQL backend database
Steps:
Home Backend Development PHP Tutorial Nginx load scheduler + dual Tomcat load and session sharing + MySQL back-end database

Nginx load scheduler + dual Tomcat load and session sharing + MySQL back-end database

Jul 07, 2018 pm 04:43 PM
mysql nginx tomcat

This article mainly introduces the Nginx load scheduler dual Tomcat load and session sharing MySQL back-end database. It has a certain reference value. Now I share it with you. Friends in need can refer to it

Nginx Load scheduler dual Tomcat load and session replication MySQL backend database

Environment:

##IPFunction192.168.2.5nginx192.168.2.6tomcat1192.168.2.7tomcat2##192.168.2.81. Configuration before session sharing
mysql

Steps:

①Close the firewall or open ports 80, 8080, 3306, close selinux

②Install nginx

从nginx官网下载最新版
wget http://nginx.org/download/nginx-1.13.9.tar.gz
Copy after login

[root@192 ~]# yum -y install pcre-devel zlib-devel gcc gcc-c make

[root@192 ~]# useradd -M -s /sbin/nologin nginx

[root@192 ~]# tar zxf nginx-1.13.9.tar.gz -C /usr/src

[root@192 ~]# cd /usr/src/nginx-1.13 .9/

[root@192 nginx-1.13.9]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_stub_status_module && make && make install

[root@192 ~]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin

Do not start nginx

③Two tomcat hosts for installation

jdk从官网下载需要许可,允许之后下载至本地,导入主机
tomcat从官网downloads找到tomcat7.0或者更高版本
wget http://mirror.bit.edu.cn/apache/tomcat/tomcat-7/v7.0.86/bin/apache-tomcat-7.0.86.tar.gz
Copy after login

[root@192 ~]# tar zxf jdk-7u65-linux-x64.gz -C /usr/src

[root@192 ~]# tar zxf apache-tomcat-7.0.54.tar.gz -C /usr/src

[root@192 ~]# mv jdk1.7.0_65/ /usr/local/ java

[root@192 ~]# mv apache-tomcat-7.0.54/ /usr/local/tomcat7

[root@192 ~]# vim /etc/profile

export JAVA_HOME=/usr/local/java
export CATALINA_HOME=/usr/local/tomcat7
export PATH=$JAVA_HOME/bin:$CATALINA_HOME/bin:$PATH
Copy after login

[root@192 ~]# source /etc/profile

[root@192 ~]# java -version

java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode)
Copy after login

[root@192 ~]# catalina.sh version

Using CATALINA_BASE:   /usr/local/tomcat7
Using CATALINA_HOME:   /usr/local/tomcat7
Using CATALINA_TMPDIR: /usr/local/tomcat7/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat7/bin/bootstrap.jar:/usr/local/tomcat7/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.
Server built:   May 19 2014 10:26:15
Server number:  7.0.86.0
OS Name:        Linux
OS Version:     3.10.0-327.el7.x86_64
Architecture:   amd64
JVM Version:    1.7.0_65-b17
JVM Vendor:     Oracle Corporation
Copy after login

Start tomcat

[root@192 ~]# /usr/local/tomcat7/bin/startup.sh

Using CATALINA_BASE:   /usr/local/tomcat7
Using CATALINA_HOME:   /usr/local/tomcat7
Using CATALINA_TMPDIR: /usr/local/tomcat7/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat7/bin/bootstrap.jar:/usr/local/tomcat7/bin/tomcat-juli.jar
Tomcat started.
Copy after login

Test access

http:// 192.168.2.6:8080

http://192.168.2.7:8080

④Two hosts modify the tomcat configuration file
[root@192 ~]#cd /usr/local/tomcat7/conf


[root@192 ~]#cp server.xml server.xml.bak

[root@192 ~]#vim server.xml

.......
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat-1">
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Context docBase="/web/webapp1" path="" reloadable="true"/>
Copy after login

[root@192 ~]#mkdir -p /web/webapp1

[root@192 ~]#vim /web/webapp1/index.jsp

<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
 <head>
<title>tomcat-1</title>
 </head>
<body>
 <h1><font color="red">Session serviced by tomcat</font></h1>
<table aligh="center" border="1">
<tr>
 <td>Session ID</td>
     <td><%=session.getId()%></td>
<% session.setAttribute("abc","abc");%>
      </tr>
<tr>
<td>Create on</td>
<td><%= session.getCreationTime() %></td>
</tr>
   </table>
</body>
</html>
Copy after login

Restart tomcat

[root@192 ~] #shutdown.sh

[root@192 ~]#startup.sh

Note: The second host is different in jvmRoute=”tomcat-2” in server.xml, and index. tomcat-2

Test access in jsp shows that the session IDs of the two tomcat hosts are different, and the preparations are completed

http://192.168.2.6 :8080

http://192.168.2.7:8008

2. Session sharing configuration

Steps:

①Configure session sharing cluster on two hosts

[root@192 ~]#vim /usr/local/tomcat7/conf/server.xml

.......
<Engine name="Catalina" defaultHost="localhost" jvmRoute="tomcat-1">

      <!--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"/>
      -->
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
                  channelSendOptions="8">

         <Manager className="org.apache.catalina.ha.session.DeltaManager"
                  expireSessionsOnShutdown="false"
                  notifyListenersOnReplication="true"/>

         <Channel className="org.apache.catal

ina.tribes.group.GroupChannel">
            <Membership className="org.apache.catalina.tribes.membership.McastService"
                        address="228.0.0.4"
                        port="45564"
                        frequency="500"
                        dropTime="3000"/>
            <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
                        address="192.168.2.5"
                        port="4000"
                        autoBind="100"
                        selectorTimeout="5000"
                        maxThreads="6"/>
            <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
              <Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
            </Sender>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
            <Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
          </Channel>

          <Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
 filter=""/>
          <Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

  <Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
                temDir="/tmp/war-temp/"
                deployDir="/tmp/war-deploy/"
                watchDir="/tmp/war-listen/"
                watchEnabled="false"/>

  <ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
      <ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
    </Cluster>
  <!-- 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">
    <Context docBase="/web/webapp1" path="" reloadable="true"/>
Copy after login

[root@192 ~]#mkdir /web/webapp1/WEB-INF

[ root@192 ~]#cp /usr/local/tomcat7/conf/web.xml WEB-INF/

[root@192 ~]#vim WEB-INF/web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">
<distributable/>  #添加这个单词,必须有这一步,否则用户的session没法使用
Copy after login

If the firewall is enabled, enable the following

[root@192 ~]#firewall-cmd --add-port=45564/udp --permanent
[root@192 ~]#firewall-cmd --add-port=4000/tcp --permanent
[root@192 ~]#firewall-cmd --reload
Restart tomcat

[root@192 ~]#shutdown.sh

[root@192 ~]#startup.sh

Note: The two tomcat configurations are the same as long as The Receiver segment refers to the IP address of the second host

②Configure nginx

[root@192 ~]#vim /usr/local/nginx/conf/nginx.conf

.......
http { 
.......
upstream tomcat_server {
        server 192.168.2.6:8080 weight=1;
        server 192.168.2.7:8080 weight=1;
  }

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://tomcat_server;
        }
Copy after login

Start nginx, visit the nginx address and refresh the page to test access

[root@192 ~]#nginx

http://192.168.2.5

3. Connection mysql database

Steps:

①The mysql container in 192.168.2.8 serves as the database server, configure mysql:

mysql>grant all privileges on

.
to javauser @'192.168.2.%' identified by '123.com';mysql> create database javatest

mysql>use javatest

mysql>create table testdata(id int not null auto_increment primary key,foo varchar(25),bar varchar(10));

mysql>insert into testdata(foo,bar) values('hello','123.com');

mysql>select * from testdata;

id1

②下载mysql-connector-java-5.1.22-bin.jar 复制到tomcat7/lib/目录下(两台tomcat都需要配置)
[root@192 ~]# cp mysql-connector-java-5.1.22-bin.jar /usr/local/tomcat7/lib/

③配置context.xml
[root@192 ~]# cp /usr/local/tomcat7/conf/context.xml /usr/local/tomcat7/conf/context.xml.bak

[root@192 ~]# vim /usr/local/tomcat7/conf/context.xml

<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="javauser" password="123.com" driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://192.168.2.8:3306/javatest"/>
Copy after login

④配置web.xml
[root@192 ~]# vim /web/webapp1/web.xml

......
<distributable/>
<description>MySQL Test App</description>
 <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/TestDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
 </resource-ref>
Copy after login

⑤编写连接数据库jsp文件
[root@192 ~]# vim /web/webapp1/test.jsp

<%@ page language="java" import="java.sql.*" pageEncoding="GB2312"%>
<html>
  <head>
    <title>MySQL</title>
  </head>
<body>
connect MySQL<br>
<%
String driverClass="com.mysql.jdbc.Driver";
String url="jdbc:mysql://192.168.2.8:3306/javatest";
String username = "javauser";
String password = "123.com";
Class.forName(driverClass);
Connection conn=DriverManager.getConnection(url, username, password);
Statement stmt=conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from testdata");
while(rs.next()){
 out.println("<br>foo:"+rs.getString(2)+"bar:"+rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
%>
</body></html>
Copy after login

⑥重启tomcat,测试连接
[root@192 ~]# shutdown.sh
[root@192 ~]# startup.sh

http://192.168.2.5/test.jsp

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

ThinkPHP5.0 Linux Apache/Nginx重写URL配置

foo bar
hello 123.com

The above is the detailed content of Nginx load scheduler + dual Tomcat load and session sharing + MySQL back-end database. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

See all articles