search
HomeBackend DevelopmentPHP TutorialNginx+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

The prompt reports the following error:

No package nginx available.

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

After installation, you can successfully install nginx;

2. Start and stop nginx

Enter the directory of nginx first

[root@localhost nginx]# cd /usr/sbin/

Execute command

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

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

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

<br> 
sessionID:   
<br>   
sessionCreateTime:
<br>

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 {
    }
}

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

Second refresh http://ip/

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

Third refresh http://ip/

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

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
}

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

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

The second Refresh http://ip/

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

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

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

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

The fifth time you refresh http://ip/

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

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

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

redis-server /etc/redis.conf

Start the client

redis-cli

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>

3.Tomcat modifies the configuration

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

<valve></valve>
<manager></manager>

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

The second time is refreshing http://ip/

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

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

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

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"

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
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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.