Take you to tomcat!Everything is here

Posted by niekos on Wed, 01 Sep 2021 20:00:54 +0200

1. Introduction to Tomcat

Tomcat is a core project of the Apache Software Foundation project, developed by Apache, Sun, and a number of other companies and individuals.

Tomcat server is a free, open source Web application server. It is a lightweight application server. It is widely used in small and medium-sized systems and in situations where concurrent access to users is not very common. It is the preferred choice for developing and debugging JSP (Java Server Pages) programs.

1. Parse java code

  • JAVA container, WEB container, WEB middleware:
Tomcat,JBOSS,resin,weblogic etc.   ---Parse Dynamic Pages
Weblogic  ---Charge.
  • Other web containers such as:
Python-------->uwsgi
php----------->fastcgi

2. Use scheme

Tomcat, like Nginx, Apache(httpd), and Web servers, has the ability to handle HTML pages, but Tomcat is not as capable of handling static HTML as the Nginx/Apache(httpd) server.

The default concurrency of a tomcat is 200 (official), which can be modified, but in practice it will be around 200 concurrencies.

https port: 443

It is recommended that you use Nginx with Tomcat, Nginx with static, Tomcat with dynamic programs
Backend Tomcat in scenario 3 can run on a separate host or on multiple instances of the same host

Tomcat: http://tomcat.apache.org

3. Tomcat Helper - JDK

JDK is the software development toolkit for Java language. JDK is the core of Java development. It contains the running environment of JAVA (JVM+Java system class library) and JAVA tools.

JDK Download Facepage:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

You currently need to register your Oracle account and log in to download the older version.

2. Basic use of Tomcat

1. Introduction to tomcat home directory

[root@java-tomcat1 ~]# cd /usr/local/tomcat
[root@java-tomcat1 tomcat]# yum install -y tree
[root@java-tomcat1 tomcat]# tree
.
├── bin     #Store the management script for tomcat
├── BUILDING.txt
├── conf    #Configuration file for tomcat
├── CONTRIBUTING.md
├── lib      #jar package store path for web application calls
├── LICENSE
├── logs     #The tomcat log holds the directory, and the catalin.out log is the output log only
├── NOTICE
├── README.md
├── RELEASE-NOTES
├── RUNNING.txt
├── temp     #Store temporary files
├── webapps  #Default Site Publishing Directory
└── work     #Store compiled.java and.class files

7 directories, 7 files

2. Introduction of webapps directory

[root@java-tomcat1 tomcat]# cd webapps/
[root@java-tomcat1 webapps]# tree
.
├── docs  #Help documentation for tomcat
├── examples  #web Application Instances
├── host-manager  #Host Management
├── manager    #Administration
└── ROOT    #Default Site Root Directory

5 directories, 0 files

3. Introduction to Tomcat Profile Directory (conf)

[root@java-tomcat1 webapps]# cd ../conf/
[root@java-tomcat1 conf]# tree
.
├── Catalina
├── catalina.policy
├── catalina.properties
├── context.xml
├── logging.properties
├── logs
├── server.xml           # tomcat master profile
├── server.xml.bak
├── server.xml.bak2
├── tomcat-users.xml    # tomcat manages user profiles
├── tomcat-users.xsd
└── web.xml

2 directories, 10 files

4. server.xml Configuration File

<?xml version='1.0' encoding='utf-8'?>
<!--
<Server>
    port Appoint Tomcat Monitor shutdown Command Port
    shutdown Specify Termination Tomcat The server is running.
-->
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.startup.VersionLoggerListener" />
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
  <GlobalNamingResources>
    <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>
  <Service name="Catalina">
    <!-- Connector Description of main parameters (see below) -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
      <!-- Details are common ( host Detailed parameters)-->
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Context path="" docBase="" debug=""/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />
      </Host>
    </Engine>
  </Service>
</Server>

(1) Description of Connector's main parameters

  • Port: Specifies the port number to be created on the server side and listens on this port for requests from clients.
  • Protocol: The protocol used by the connector to support HTTP and AJP.AJP (Apache Jserv Protocol) is designed for tomcat to communicate with apache.
  • redirectPort: Specifies the port number to redirect when the server receives an SSL transport request while processing an http request
  • maxThreads: Maximum number of concurrent requests received
  • ConneionTimeout specifies the number of time-outs in milliseconds

As shown in the diagram

(2) Detailed host parameters

  • Host:Represents a virtual host
  • Name:Specify host name
  • AppBase: The application base directory, which is the directory where the application is stored. Typically, appBase="webapps", relative to CATALINA_For HOME, absolute paths can also be written.
  • unpackWARs: If true, tomcat will automatically unzip the WAR file, otherwise run the application directly from the WAR file without unzipping it
  • autoDeploy: Whether to deploy automatically when tomcat starts

5. Management of Tomcat

Start Program #/usr/local/tomcat/bin/startup.sh  #start-up
 close program #/usr/local/tomcat/bin/shutdown.sh #Close

start-up

[root@java-tomcat1 conf]# cd ../bin/
[root@java-tomcat1 bin]# ./startup.sh 
Using CATALINA_BASE:   /data/application/tomcat
Using CATALINA_HOME:   /data/application/tomcat
Using CATALINA_TMPDIR: /data/application/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /data/application/tomcat/bin/bootstrap.jar:/data/application/tomcat/bin/tomcat-juli.jar
Tomcat started.

Note: When tomcat is not started using the shutdown script, there is a lot of output information.

Check if tomcat is started properly

[root@tomcat1 bin]# netstat -lntp  |grep java
tcp6       0      0 127.0.0.1:8005          :::*                    LISTEN      1546/java
tcp6       0      0 :::8080                 :::*                    LISTEN      1546/java
[root@tomcat1 bin]#

6. Port number

  • 8005: This port is responsible for listening for requests to close Tomcat.Can be modified (line 22 of conf/server.xml)

    shutdown.sh: The command string sent to port 8005 to shut down the server.

  • 8080: Establish http, also known as client access connection.Can be modified (69 lines conf/server.xml)

  • 8009: Communication interface with other http services. (116 lines of conf/server.xml)

Launch to complete browser access, default page is as follows

7. View Logs

[root@java-tomcat1 bin]# tail -f /usr/local/tomcat/logs/catalina.out 
org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/data/application/tomcat/webapps/host-manager] has finished in [21] ms
04-Jul-2019 22:40:00.026 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [/data/application/tomcat/webapps/manager]
04-Jul-2019 22:40:00.042 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [/data/application/tomcat/webapps/manager] has finished in [16] ms
04-Jul-2019 22:40:00.048 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8080"]
04-Jul-2019 22:40:00.058 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["ajp-nio-8009"]
04-Jul-2019 22:40:00.062 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 479 ms

8. WEB Site Deployment

(1) Deploy a web site using the war package

There are two ways to get code online:

  • The first is to place the program directory directly under the webapps directory.

  • The second option is to package the program into a war package using a development tool and upload it to the webapps directory.

[root@java-tomcat1 ~]# pwd
/root
 download jenkins Of war package
[root@java-tomcat1 ~]# wget http://updates.jenkins-ci.org/download/war/2.129/jenkins.war
[root@java-tomcat1 ~]# ls
jenkins.war                
[root@java-tomcat1 ~]# cd /user/local/tomcat   #Enter tomcat directory
[root@java-tomcat1 tomcat]# cp -r webapps/ /opt/    #Back up the original publishing site directory
[root@java-tomcat1 tomcat]# cd webapps/
[root@java-tomcat1 webapps]# ls
docs  examples  host-manager  manager  ROOT
[root@java-tomcat1 webapps]# rm -rf *    #Empty the content of the publishing site
[root@java-tomcat1 webapps]# cp /root/jenkins.war .   #Copy the war package to the current directory
[root@java-tomcat1 webapps]# ../bin/startup.sh   #start-up
Using CATALINA_BASE:   /data/application/tomcat
Using CATALINA_HOME:   /data/application/tomcat
Using CATALINA_TMPDIR: /data/application/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /data/application/tomcat/bin/bootstrap.jar:/data/application/tomcat/bin/tomcat-juli.jar
Tomcat started.
[root@java-tomcat1 webapps]# ls
jenkins  jenkins.war

2. Manual decompression:
[root@java-tomcat1 webapps]# ../bin/shutdown.sh   #Turn off tomcat
[root@java-tomcat1 ~]# cd /usr/local/tomcat/webapps/
[root@java-tomcat1 webapps]# rm -rf *    
[root@java-tomcat1 webapps]# mkdir ROOT      #Create a ROOT directory to store the war package
[root@java-tomcat1 webapps]# ls
ROOT
[root@java-tomcat1 webapps]# cd ROOT/
[root@java-tomcat1 ROOT]# cp /root/jenkins.war .
[root@java-tomcat1 ROOT]# unzip jenkins.war

Browser access: http://192.168.1.7:8080/jenkins

(2) Customize the default site directory

1. Modify the default publishing directory:

[root@java-tomcat1 ~]# mkdir -p /data/application/webapp  #Create Publication Directory
[root@java-tomcat1 ~]# vim /usr/local/tomcat/conf/server.xml

Will be the original

Modify to

[root@java-tomcat1 ~]# cp /root/jenkins.war /data/application/webapp/
[root@java-tomcat1 ~]# /usr/local/tomcat/bin/startup.sh
Using CATALINA_BASE:   /usr/local/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /usr/local/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Tomcat started.
[root@java-tomcat1 ~]# ll /data/application/webapp/   #Automatically decompressed
jenkins/     jenkins.war

(3) Deploy open source sites (jspgou Shop)

First milestone: installing the configuration database

[root@java-tomcat1 ~]# wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm
[root@java-tomcat1 ~]# rpm -ivh mysql80-community-release-el7-3.noarch.rpm
[root@java-tomcat1 ~]# cd /etc/yum.repos.d/
[root@java-tomcat1 yum.repos.d]# vim mysql-community.repo
 Be careful enabled Middle 0 means off and 1 means on

Modify as follows

install
[root@java-tomcat1 yum.repos.d]# yum -y install mysql-server mysql
[root@java-tomcat1 yum.repos.d]# cd
[root@java-tomcat1 ~]# systemctl start mysqld
[root@java-tomcat1 ~]# systemctl enable mysqld
 Find and change your password
[root@java-tomcat1 ~]# grep pass /var/log/mysqld.log   #Filter Find Password
2019-07-05T15:57:15.294365Z 1 [Note] A temporary password is generated for root@localhost: %6yx817IeX-J
[root@java-tomcat1 ~]# mysqladmin -u root -p'%6yx817IeX-J' password 'QianFeng@123' #Change Password

Configuration database

[root@java-tomcat1 ~]# mysql -u root -p'QianFeng@123'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3


mysql> create database jspgou default charset=utf8;  #Create database settings character set
Query OK, 1 row affected (0.00 sec)

mysql> \q
Bye

Second milestone: jspgou Shop Online

upload jspgou Shop Code
[root@java-tomcat1 ~]# unzip jspgouV6.1-ROOT.zip
[root@java-tomcat1 ~]# cp -r ROOT/ /data/application/tomcat/webapps/
[root@java-tomcat1 ~]# cd /data/application/tomcat/webapps/
[root@java-tomcat1 webapps]# ls
ROOT
[root@java-tomcat1 webapps]# vim ROOT/WEB-INF/config/jdbc.properties

Configure Database Connection - jdbc

Import data into database:
[root@java-tomcat1 ~]# cd DB/
[root@java-tomcat1 DB]# ls
jspgou.sql
[root@java-tomcat1 DB]# mysql -uroot -p'QianFeng@123' -D jspgou < jspgou.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1067 (42000) at line 97: Unknown error 1067
[root@java-tomcat1 DB]# Vim/etc/my.cnf - - add sql_mod
sql_mode=STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUB
explicit_defaults_for_timestamp=1
[root@java-tomcat1 DB]# systemctl restart mysqld
[root@java-tomcat1 DB]# mysql -uroot -p'QianFeng@123' -D jspgou < jspgou.sql
 start-up tomcat Visit:
[root@java-tomcat1 ~]# /usr/local/tomcat/bin/startup.sh
[root@java-tomcat1 ~]# netstat -lntp

Visit: http://192.168.1.7:8080/

3. Tomcat multi-instance configuration

Multiple Instances (Multiple Processes): The same program is started multiple times, in two cases:

First, one machine runs multiple stations;

Second: a machine running multiple instances of a site, with load balancing

1. Copy program files

[root@java-tomcat1 ~]# cd /usr/local
[root@java-tomcat1 local]# ls
tomcat
[root@java-tomcat1 local]# cp -r tomcat/ tomcat_2
[root@java-tomcat1 local]# ls
tomcat  tomcat_2
 Modify the port to start multiple instances.Port inconsistency between multiple instances
[root@java-tomcat1 local]# sed -i 's#8005#8011#;s#8080#8081#' tomcat/conf/server.xml
[root@java-tomcat1 local]# sed -i 's#8005#8012#;s#8080#8082#' tomcat_2/conf/server.xml
[root@java-tomcat1 local]# sed -i 's#8009#8019#' tomcat/conf/server.xml
[root@java-tomcat1 local]# sed -i 's#8009#8029#' tomcat_2/conf/server.xml
[root@java-tomcat1 local]# diff tomcat/conf/server.xml tomcat_2/conf/server.xml  #Compare file differences
22c22
< <Server port="8011" shutdown="SHUTDOWN">
---
> <Server port="8012" shutdown="SHUTDOWN">
67c67
<          Define a non-SSL/TLS HTTP/1.1 Connector on port 8081
---
>          Define a non-SSL/TLS HTTP/1.1 Connector on port 8082
69c69
<     <Connector port="8081" protocol="HTTP/1.1"
---
>     <Connector port="8082" protocol="HTTP/1.1"
75c75
<                port="8081" protocol="HTTP/1.1"
---
>                port="8082" protocol="HTTP/1.1"
115,116c115,116
<     <!-- Define an AJP 1.3 Connector on port 8019 -->
<     <Connector port="8019" protocol="AJP/1.3" redirectPort="8443" />
---
>     <!-- Define an AJP 1.3 Connector on port 8029 -->
>     <Connector port="8029" protocol="AJP/1.3" redirectPort="8443" />

Start tomcat multi-instance

[root@java-tomcat1 local]# cp -r /opt/webapps/ROOT/ tomcat/webapps/
[root@java-tomcat1 local]# cp -r /opt/webapps/ROOT/ tomcat_2/webapps/
[root@java-tomcat1 local]# echo 8081 >> tomcat/webapps/ROOT/index.jsp 
[root@java-tomcat1 local]# echo 8082 >> tomcat_2/webapps/ROOT/index.jsp
 Start:
[root@java-tomcat1 local]# cd tomcat_2/bin/
[root@java-tomcat1 bin]# vim start.sh
#!/bin/bash
#tomcat_2
export CATALINA_BASE="/usr/local/tomcat_2"

case "$1" in

start)
    $CATALINA_BASE/bin/startup.sh
    ;;
stop)
    $CATALINA_BASE/bin/shutdown.sh
esac
[root@java-tomcat1 bin]# chmod +x start.sh
#Modify catalina.sh - - add the following
[root@java-tomcat1 bin]# vim catalina.sh
CATALINA_HOME=/usr/local/tomcat_2  #Attention to modifying environment variables added
[root@java-tomcat1 bin]# cd /usr/local/tomcat/bin/
[root@java-tomcat1 bin]# vim start.sh
#!/bin/bash
#tomcat
export CATALINA_BASE="/usr/local/tomcat"

case "$1" in

start)
    $CATALINA_BASE/bin/startup.sh
    ;;
stop)
    $CATALINA_BASE/bin/shutdown.sh
esac
[root@java-tomcat1 bin]# chmod +x start.sh
[root@java-tomcat1 bin]# vim catalina.sh
CATALINA_HOME=/usr/local/tomcat
# If multiple-instance deployments use different JDK versions, modify catalina.sh and define java here
JAVA_HOME=
JRE_HOME=


start-up:
[root@java-tomcat1 ~]# /usr/local/tomcat/bin/start.sh start
[root@java-tomcat1 ~]# /usr/local/tomcat_2/bin/start.sh start

Check the port to see if it is started:

[root@java-tomcat1 application]# netstat -lntp | grep java 
tcp6       0      0 127.0.0.1:8011          :::*                    LISTEN      1729/java           
tcp6       0      0 127.0.0.1:8012          :::*                    LISTEN      1783/java           
tcp6       0      0 :::8081                 :::*                    LISTEN      1729/java           
tcp6       0      0 :::8082                 :::*                    LISTEN      1783/java           
tcp6       0      0 :::8019                 :::*                    LISTEN      1729/java           
tcp6       0      0 :::8029                 :::*                    LISTEN      1783/java

2. Testing

Check multi-instance startup

http://192.168.50.114:8081/

http://192.168.50.114:8082/

4. tomcat reverse proxy cluster

1. Load Balancer Description

Close firewall and selinux

yum install nginx
[root@nginx-proxy ~]# cd /etc/yum.repos.d/
[root@nginx-proxy yum.repos.d]# vim nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1
[root@nginx-proxy yum.repos.d]# yum install yum-utils -y
[root@nginx-proxy yum.repos.d]# yum install nginx -y

2. Configure Load Balancer

Back up the original configuration file and modify it

[root@nginx-proxy ~]# cd /etc/nginx/conf.d/
[root@nginx-proxy conf.d]# vim  default.conf
server {
    listen       80;
    server_name  localhost;
    access_log  /var/log/nginx/proxy.access.log  main;

    location / {
       proxy_pass http://testweb;
       proxy_set_header Host $host:$server_port;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }       
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    } 
}
Establish upstream configuration file:
[root@nginx-proxy conf.d]# vim upstream.conf
upstream testweb {
	server 192.168.50.114:8081 weight=1 max_fails=1 fail_timeout=2s;
	server 192.168.50.114:8082 weight=1 max_fails=1 fail_timeout=2s;
}

start nginx

[root@nginx-proxy ~]# systemctl start nginx

3. Use commands for access testing

Use curl command for testing, tail for keyword extraction

[root@nginx-proxy ~]# curl  192.168.50.118 | tail -1 
8082
[root@nginx-proxy ~]# curl  192.168.50.118 | tail -1 
8081
4. Access testing on browsers

http://192.168.50.118/

http://192.168.50.118/

5. Common sense of JVM virtual machines

1. What is a JAVA virtual machine

A virtual machine is a virtual computer.He is software that executes a series of virtual computer instructions.In general, virtual machines can be divided into system and program virtual machines.The well-known VisualBox and VMware belong to the system virtual machine.They are entirely simulation of physical computers.Provides a software platform that runs a complete operating system.
A typical representation of a program virtual machine is the Java virtual machine, which is designed to execute a single computer program. Instructions executed in a Java virtual machine are called Java byte code instructions.

2. How JAVA can cross-platform

The same JAVA program runs on major mainstream operating system platforms through the JAVA Virtual Machine (JVM)
For example, Windows, CentOS, Ubuntu, etc.Programs use virtual machines as intermediaries to achieve cross-platform.

3. Virtual Machine Heap Memory Structure (pre-1.8)

We want to have a perceptual understanding of the structure of the JVM virtual machine.After all, we're not programmers, and we don't have that deep understanding.

The heap space in a JVM can be divided into three large regions, the younger generation, the older generation and the permanent generation (the method area).

  • Cenozoic: Cenozoic area (divided into Eden area and S0, S1 area)
    Classes are generated and applied here and are eventually garbage collected.All objects are new out of this area. When the area is full, the GC destroys the unused objects in this area, leaving useful transitions to the surviving area.
  • Older Ages: Older Areas
    Used to store objects with a longer generation cycle.
  • Permanent Generation: Permanent Area
    Store the class,interface that comes with JDK.

Interpretation: I am a normal Java object. I was born in Eden area. In Eden area, I also see my little brother who looks like me. We played in Eden area for a long time.One day there were so many people in Eden that I was forced to go to the From area of Survivor. Since I went to the Survivor area, I've been floating. Sometimes in the From area of Survivor, sometimes in the To area of Survivor, I have no place to live.Until I was 18 years old, my father said I was an adult and it was time to make a social break.So I went to the old generation, there are many people in the old generation, and they are very old. I also know a lot of people here.In the older generation, I lived for 20 years (one year plus one year per GC) and was recycled.

There are two types of jvm regions in general, heap and non-heap.

  • heap is divided into Eden Space, Survivor Space, form and to, and Tenured Gen.
  • Non-heap areas are divided into Code Cache, Perm Gen, Jvm Stack, Local Method Statck.

4. Common JVM parameters

(1) Configure heap space for the JAVA virtual machine

-Xms:Initial heap size
-Xmx:Maximum heap size
–XX: NewRatio =3    //The ratio of new domain to old domain is 1:3
 In a real production environment, we usually initialize the heap(-Xms) And Max heap(-Xmx) Set to the same size.To avoid applications frequently requesting heap space.Set to half of physical memory.
[root@java-tomcat1 bin]# vim catalina.sh adds
JAVA_OPTS="$JAVA_OPTS -Xms1024m -Xmx1024m"

(2) Open GC log

GC log: JVM garbage collection, record the running status of jvm, error information of oom memory overflow, etc. (Track garbage collection of JAVA virtual machines)

  • %t will be replaced with a time string in the format YYYY-MM-DD_HH-MM-SS

Open GC log:

[root@java-tomcat1 bin]# vim catalina.sh adds
JAVA_OPTS="$JAVA_OPTS  -Xms1024m -Xmx1024m -Xloggc:/data/logs/gc-%t.log"
[root@java-tomcat1 bin]# mkdir -p /data/logs
 restart tomcat

6. Practical obstacle removal tools for JVM operation and maintenance

1,jps

Used to view the specific state of a Java process, including the process ID, the path to start the process, the startup parameters, etc., similar to ps on unix, except that jps is used to display Java processes

Common parameters are as follows:

  • -v: output parameters passed to jvm

Note: The running account when using jps should be the same as the account started by the JVM virtual machine.If the account under which the JVM virtual machine is started is www, the WW user is also used to specify when using the jps directive.

sudo -u www jps

View the actual startup parameters of a running JVM process

[root@java-tomcat1 ~]# jps -v 
58154 Jps -Denv.class.path=.:/usr/local/java/lib:/usr/local/java/jre/lib:/usr/local/java/lib/tools.jar -Dapplication.home=/usr/local/java -Xms8m
58015 Bootstrap -Djava.util.logging.config.file=/data/application/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -Dcatalina.base=/data/application/tomcat -Dcatalina.home=/data/application/tomcat -Djava.io.tmpdir=/data/application/tomcat/temp

2,jstack

jstack is used to print out the Java stack information for a given java process ID or remote debugging service.This information is usually saved during maintenance (to save the failure site) for RD (developers) to analyze the failure.
Common parameters are as follows:

  • jstack
  • jstack [-l] //long list. Print additional information about locks
  • jstack [-F] //Force the printing of stack information when'jstack [-l] pid'does not respond

Print stack information for JVM to troubleshoot

[root@mouse03 ~]# jstack -F 38360 > /tmp/jstack.log

7. Tomcat security optimization

Declining Start (Mandatory)

categoryConfiguration and descriptionStandard ConfigurationRemarks
Declining Start1. The tomcat startup user rights must be non-root rights, minimizing the directory access rights of the tomcat startup user;2. If you need to use port 80 directly, you can configure iptables rules to forward after ordinary account is started.Avoid compromising the security of the entire server by hackers directly obtaining advanced user privileges once the tomcat service is compromised;
[root@java-tomcat1 ~]# useradd tomcat 
[root@java-tomcat1 ~]# chown tomcat.tomcat /usr/local/tomcat/ -R
[root@java-tomcat1 ~]# su -c '/usr/local/tomcat/bin/start.sh start' tomcat 
Using CATALINA_BASE:   /data/application/tomcat
Using CATALINA_HOME:   /data/application/tomcat
Using CATALINA_TMPDIR: /data/application/tomcat/temp
Using JRE_HOME:        /usr/local/java
Using CLASSPATH:       /data/application/tomcat/bin/bootstrap.jar:/data/application/tomcat/bin/tomcat-juli.jar
Tomcat started.
[root@java-tomcat1 ~]# ps -ef | grep tomcat 
tomcat     1065      1 64 20:33 ?        00:00:06 /usr/local/java/bin/java -Djava.util.logging.config.file=/data/applicationtomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dignore.endorsed.dirs= -classpath /data/application/tomcat/bin/bootstrap.jar:/data/application/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/data/application/tomcat -Dcatalina.home=/data/application/tomcat -Djava.io.tmpdir=/data/application/tomcat/temp org.apache.catalina.startup.Bootstrap start
root       1112   1027  0 20:33 pts/0    00:00:00 grep --color=auto tomcat

8. Tomcat Performance Optimization

  • Top Policy: Optimize Code

    This project requires sufficient experience and high requirements for developers

  • Medium strategy: jvm optimization mechanism Garbage collection mechanism recycles unwanted memory
    Optimize jvm - Optimize garbage collection strategy
    Optimize the catalina.sh configuration file.Add code to the catalina.sh configuration file

    # tomcat allocate 1G heap memory template
    JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m 
    # Restart Service
    su -c '/home/tomcat/tomcat8_1/bin/shutdown.sh' tomcat
    su -c '/home/tomcat/tomcat8_1/bin/startup.sh' tomcat
    
  • Policy: Add enough memory (the project has a large capital investment)

  • The next step: restart tomcat at 0:00 a.m. every day (more widely used)

9. Setting up JVM cache

After the host name is resolved to an IP address, the resource IP address is saved in the JVM cache.If you change the IP address of the resource, you need to restart the application server so that Identity Manager can detect the changes (ID-3635).This is a setting in Sun JDK (1.3 and later) and can be controlled using the sun.net.inetaddr.ttl property (usually set in jre/lib/security/java.security)

Sets the validity time of the cache in the JVM for successfully resolved domain name records. By default, the JVM is always valid, so that domain name IP redirection must restart the JVM, where the change is valid for 5 seconds, 0 means no caching, and -1 means always valid

java.security.Security.setProperty("networkaddress.cache.ttl", "5");

//Set the domain name resolution failure to record the valid time of the cache in the JVM, which defaults to 10 seconds, 0 to disable caching, and -1 to always be valid

java.security.Security.setProperty("networkaddress.cache.negative.ttl", "2");

There are two ways to set up a dns cache

  • Mode 1: In JAVA_Settings in OPTS
-Dsun.net.inetaddr.ttl=3 -Dsun.net.inetaddr.negative.ttl=1
  • Mode 2: Modify property
System.setProperty("sun.net.inetaddr.ttl", "3");
System.setProperty("sun.net.inetaddr.negative.ttl", "1");

Topics: Java Linux jvm Tomcat