Table of Contents
Preface
nginx installation configuration
1. Install nginx
2. Start and stop nginx
nginx tomcat load balancing
1. Prepare 2 tomcats, specify ports 8081 and 8082 respectively
2.nginx configuration load balancing (default Strategy)
3.nginx configuration load balancing (sticky Session)
nginx tomcat implementation Session sharing
1.redis installation configuration
2.Tomcat introduces dependent jar
3.Tomcat modifies the configuration
4. Test
Home Backend Development PHP Tutorial Nginx+Tomcat about Session management

Nginx+Tomcat about Session management

Jul 07, 2018 pm 04:16 PM
nginx

This article mainly introduces the session management of Nginx Tomcat, which has certain reference value. Now I share it with you. Friends in need can refer to it

Preface

Nginx Tomcat has always understood the management of Session, but has never practiced it. This article starts from the simplest installation and startup, and gradually introduces several ways to manage sessions through examples.

nginx installation configuration

1. Install nginx

[root@localhost ~]# yum install nginx
Copy after login

The prompt reports the following error:

No package nginx available.
Copy after login

Solution to install epel: EPEL EPEL is the abbreviation of Enterprise Linux Add-on Package. EPEL is created, maintained and managed by the Fedora Special Interest Group for Red Hat Enterprise Linux (RHEL) and its derivative distributions (such as CentOS, Scientific Linux, Oracle Enterprise Linux) A high-quality additional software package project;

[root@localhost ~]# yum install epel-release
Copy after login

After installation, you can successfully install nginx;

2. Start and stop nginx

Enter the directory of nginx first

[root@localhost nginx]# cd /usr/sbin/
Copy after login

Execute command

./nginx 开启
./nginx -s stop  使用kill命令强制杀掉进程
./nginx -s quit  待nginx进程处理任务完毕进行停止
./nginx -s reload
Copy after login

nginx tomcat load balancing

1. Prepare 2 tomcats, specify ports 8081 and 8082 respectively

drwxr-xr-x. 9 root root      4096 May  7 14:16 apache-tomcat-7.0.88_8081
drwxr-xr-x. 9 root root      4096 May  7 14:16 apache-tomcat-7.0.88_8082
Copy after login

Modify the index.jsp of webapps/ROOT to facilitate testing

<%
if(request.getSession().getAttribute("key")==null){
   out.println("key is null,ready init.....");   
   request.getSession().setAttribute("key","value");
}else{
   out.println("key is not null,key="+request.getSession().getAttribute("key"));  
}
%>
<br> 
sessionID:<%=session.getId()%>   
<br>   
sessionCreateTime:<%= session.getCreationTime() %>
<br>
<% 
out.println("tomcat port 8081");   
%>
Copy after login

The final output specifies the respective port numbers 8081 and 8082 under the two tomcats

2.nginx configuration load balancing (default Strategy)

Modify nginx.conf under /etc/nginx/

upstream tomcatTest {
     server 127.0.0.1:8081;   #tomcat-8081
     server 127.0.0.1:8082;   #tomcat-8082
}
 
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         /usr/share/nginx/html;
 
    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;
 
    location / {
        proxy_pass http://tomcatTest;
    }
 
    error_page 404 /404.html;
        location = /40x.html {
    }
 
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}
Copy after login

The load balancing strategy configured here is the default polling strategy. nginx also supports other strategies including: ip_hash, weight , fair (third party), url_hash (third party);
Default policy Each web request is assigned to different back-end servers one by one in chronological order. In this case, a new session will be created for each request. Do the following Simple test:
First request http://ip/

key is null,ready init..... 
sessionID:E7A9782DED29FF04E21DF94078CB4F62 
sessionCreateTime:1527732911441
tomcat port 8082
Copy after login

Second refresh http://ip/

key is null,ready init..... 
sessionID:7812E8E21DBB74CC7FBB75A0DFF2E9CB 
sessionCreateTime:1527732979810
tomcat port 8081
Copy after login

Third refresh http://ip/

key is null,ready init..... 
sessionID:8895F41E299785A21995D5F8BB734B86 
sessionCreateTime:1527733011878
tomcat port 8082
Copy after login

It can be found that a new session is generated every time, and the messages are distributed to different back-end servers one by one in chronological order. Generally, websites that need to maintain sessions are not allowed to generate a session for each request. ;

3.nginx configuration load balancing (sticky Session)

Each request is allocated according to the hash result of the access IP, so that each visitor has a fixed access to a back-end server, which can solve the problem of session Question; nginx can achieve sticky Session by configuring ip_hash in the upstream module;

upstream tomcatTest {
     ip_hash;
     server 127.0.0.1:8081;   #tomcat-8081
     server 127.0.0.1:8082;   #tomcat-8082
}
Copy after login

Do a simple test below:
The first request is http://ip/

key is null,ready init..... 
sessionID:859BADFB09A4ECEAEC5257F518C228A0 
sessionCreateTime:1527734181450
tomcat port 8081
Copy after login

The second Refresh http://ip/

key is not null,key=value 
sessionID:859BADFB09A4ECEAEC5257F518C228A0 
sessionCreateTime:1527734181450
tomcat port 8081
Copy after login
Copy after login

for the third time and refresh http://ip/

key is not null,key=value 
sessionID:859BADFB09A4ECEAEC5257F518C228A0 
sessionCreateTime:1527734181450
tomcat port 8081
Copy after login
Copy after login

for the third time. You can find that key=value is set in the first request, and it can be obtained every time thereafter. To the key value, the sessionId has not changed, and tomcat has not changed, achieving a sticky Session;
At this time, you can stop tomcat with port=8081, and then observe
The fourth refresh of http://ip/

key is null,ready init..... 
sessionID:3C15FE2C8E8A9DCDC6EAD48180B78B80 
sessionCreateTime:1527735994476
tomcat port 8082
Copy after login

The fifth time you refresh http://ip/

key is not null,key=value 
sessionID:3C15FE2C8E8A9DCDC6EAD48180B78B80 
sessionCreateTime:1527735994476
tomcat port 8082
Copy after login

you can find that the message is forwarded to tomcat-8082, and the session is lost, and a new session is re-created;
How to make this In this case, the session is not lost, and there are two solutions: Session replication and Session sharing; Session sharing is better in terms of scalability and performance. The following focuses on how to implement Session sharing;

nginx tomcat implementation Session sharing

The idea of ​​Session sharing is to save the session in a public place and then take it out when used. The specific public place can be: redis, db, memcached, etc., as follows redis is an instance

1.redis installation configuration

yum install redis
Copy after login

After the installation is complete, configure the file /etc/redis.conf
Start the redis server

redis-server /etc/redis.conf
Copy after login

Start the client

redis-cli
Copy after login

2.Tomcat introduces dependent jar

$TOMCAT_HOME/lib and adds the following jar package

<dependency>
    <groupId>com.bluejeans</groupId>
    <artifactId>tomcat-redis-session-manager</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.5.2</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.2</version>
</dependency>
Copy after login

3.Tomcat modifies the configuration

Modify $TOMCAT_HOME/conf The context.xml file in the directory

<Valve className="com.orangefunction.tomcat.redissessions.RedisSessionHandlerValve" />
<Manager className="com.orangefunction.tomcat.redissessions.RedisSessionManager"
         host="localhost"
         port="6379"
         database="0"
         maxInactiveInterval="60"/>
Copy after login

Tomcat provides an open session management and persistence org.apache.catalina.session.ManagerBase. By inheriting this abstract class and making some simple configurations, you can Your session management class takes over Tomcat's session reading and persistence. Here, tomcat-redis-session-manager is used to manage the session;
RedisSessionManager inherits from the org.apache.catalina.session.ManagerBase class and is responsible for the session. Related operations are all in this category;

4. Test

The first request is http://ip/

key is null,ready init..... 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8081
Copy after login

The second time is refreshing http://ip/

key is not null,key=value 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8081
Copy after login

Stop tomcat-8081 and refresh http://ip/

key is not null,key=value 
sessionID:1131499E5A65DE1591152465E7B24B1F 
sessionCreateTime:1527740273682
tomcat port 8082
Copy after login

for the third time. You can find that the message has been forwarded to the tomcat-8082 node, but the session has not changed. At the same time, the key can also get the value;

5. Check redis

[root@localhost ~]# redis-cli
127.0.0.1:6379> keys *
1) "1131499E5A65DE1591152465E7B24B1F"
127.0.0.1:6379> get 1131499E5A65DE1591152465E7B24B1F
"\xac\xed\x00\x05sr\x00Dcom.orangefunction.tomcat.redissessions.SessionSerializationMetadataB\xd9\xd9\xf7v\xa2\xdbL\x03\x00\x01[\x00\x15sessionAttributesHasht\x00\x02[Bxpw\x14\x00\x00\x00\x10}\xc8\xc9\xcf\xf6\xc3\xb5Y\xc7\x0c\x8eF\xa5\xfaQ\xe8xsr\x00\x0ejava.lang.Long;\x8b\xe4\x90\xcc\x8f#\xdf\x02\x00\x01J\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b\x02\x00\x00xp\x00\x00\x01c\xb4j\x94\x12sq\x00~\x00\x03\x00\x00\x01c\xb4j\x94\x12sr\x00\x11java.lang.Integer\x12\xe2\xa0\xa4\xf7\x81\x878\x02\x00\x01I\x00\x05valuexq\x00~\x00\x04\x00\x00\a\bsr\x00\x11java.lang.Boolean\xcd r\x80\xd5\x9c\xfa\xee\x02\x00\x01Z\x00\x05valuexp\x01q\x00~\x00\nsq\x00~\x00\x03\x00\x00\x01c\xb4j\x94*t\x00 1131499E5A65DE1591152465E7B24B1Fsq\x00~\x00\a\x00\x00\x00\x01t\x00\x03keyt\x00\x05valuew\b\x00\x00\x01c\xb4j\x94\x12"
Copy after login

and you can find that the session object has been stored in redis, and the sessionId is used as the key value to store the binary data of the session;

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

The above is the detailed content of Nginx+Tomcat about Session management. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 allow external network access to tomcat server How to allow external network access to tomcat server Apr 21, 2024 am 07:22 AM

To allow the Tomcat server to access the external network, you need to: modify the Tomcat configuration file to allow external connections. Add a firewall rule to allow access to the Tomcat server port. Create a DNS record pointing the domain name to the Tomcat server public IP. Optional: Use a reverse proxy to improve security and performance. Optional: Set up HTTPS for increased security.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Welcome to nginx!How to solve it? Welcome to nginx!How to solve it? Apr 17, 2024 am 05:12 AM

To solve the "Welcome to nginx!" error, you need to check the virtual host configuration, enable the virtual host, reload Nginx, if the virtual host configuration file cannot be found, create a default page and reload Nginx, then the error message will disappear and the website will be normal show.

How to generate URL from html file How to generate URL from html file Apr 21, 2024 pm 12:57 PM

Converting an HTML file to a URL requires a web server, which involves the following steps: Obtain a web server. Set up a web server. Upload HTML file. Create a domain name. Route the request.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

What are the most common instructions in a dockerfile What are the most common instructions in a dockerfile Apr 07, 2024 pm 07:21 PM

The most commonly used instructions in Dockerfile are: FROM: Create a new image or derive a new image RUN: Execute commands (install software, configure the system) COPY: Copy local files to the image ADD: Similar to COPY, it can automatically decompress tar archives or obtain URL files CMD: Specify the command when the container starts EXPOSE: Declare the container listening port (but not public) ENV: Set the environment variable VOLUME: Mount the host directory or anonymous volume WORKDIR: Set the working directory in the container ENTRYPOINT: Specify what to execute when the container starts Executable file (similar to CMD, but cannot be overwritten)

Can nodejs be accessed from the outside? Can nodejs be accessed from the outside? Apr 21, 2024 am 04:43 AM

Yes, Node.js can be accessed from the outside. You can use the following methods: Use Cloud Functions to deploy the function and make it publicly accessible. Use the Express framework to create routes and define endpoints. Use Nginx to reverse proxy requests to Node.js applications. Use Docker containers to run Node.js applications and expose them through port mapping.

How to deploy and maintain a website using PHP How to deploy and maintain a website using PHP May 03, 2024 am 08:54 AM

To successfully deploy and maintain a PHP website, you need to perform the following steps: Select a web server (such as Apache or Nginx) Install PHP Create a database and connect PHP Upload code to the server Set up domain name and DNS Monitoring website maintenance steps include updating PHP and web servers, and backing up the website , monitor error logs and update content.

See all articles