Solve the session sharing problem of nginx load balancing
I checked some information and read some documents written by others. The summary is as follows, to realize the sharing of nginx session.
There are multiple PHP servers. Use nginx for load balancing, so that the same IP accessing the same page will be assigned to different servers. On the server, if the session is not synchronized, many problems will occur, such as the most common login status. Here are several ways to solve the problem of session sharing:
1. Do not use session, use cookie instead
session It is stored on the server side, and the cookie is stored on the client side. We can put the session generated by the user's visit to the page into the cookie, which is to use the cookie as the transfer station. You visit web server A, generate a session and put it in a cookie. When your request is assigned to server B, server B first determines whether the server has the session. If not, it then checks to see if it is in the client's cookie. If there is no such session, it means that the session really does not exist. If there is one in the cookie, synchronize the session in the cookie to server B, so that the session can be synchronized.
Note: This method is simple and convenient to implement, and will not increase the burden on the database. However, if the client disables cookies, the session will not be synchronized, which will cause losses to the website; cookie The security is not high. Although it is encrypted, it can still be forged.
2. The session is stored in the database (MySQL, etc.)
PHP can be configured to save the session in the database. This method is to put the table storing the session together with other database tables. If MySQL is also clustered, Each mysql node must have this table, and the data table of this session table must be synchronized in real time.
Note: Using a database to synchronize sessions will increase the IO of the database and increase the burden on the database. Moreover, the database reading and writing speed is slow, which is not conducive to timely synchronization of sessions.
3. The session is stored in memcache or redis
memcache can be distributed. The storage method is set to memcache in the php configuration file, so that php itself will establish a session cluster and store the session data in memcache.
Note: Synchronizing the session in this way will not increase the burden on the database, and the security is greatly improved compared to using cookies. Putting the session in the memory is much faster than reading from the file. However, memcache divides the memory into storage blocks of many specifications, and each block has its own size. This method also determines that memcache cannot fully utilize the memory and will produce memory fragmentation. If there are not enough storage blocks, memory overflow will occur.
4. The ip_hash technology in nginx can direct the request of a certain IP to the same backend, so that a certain client and a certain backend under this IP can establish a stable session. ip_hash is Definition in the upstream configuration:
- stream nginx.example.com {
- Server 192.168.74.235:80;
- Server 192.168.74.236:80;
- ip_hash;
- }
- server
- {
- listen 80;
- location /
- {
- proxy_pass
- http://nginx.example.com ;
- .nginx is not a front-end server. ip_hash requires nginx to be the front-end server, otherwise nginx cannot get the correct IP and cannot hash based on the IP. For example, if Squid is used as the front end, then nginx can only get the Squid server IP address when fetching the IP. It is definitely confusing to use this address for distribution.
- 2. The backend of nginx also has other methods of load balancing.
If the nginx backend has other load balancing and the requests are diverted through other methods, then a request from a certain client will definitely not be located on the same session application server. Calculated this way, the nginx backend can only point directly to the application server, or build a Squid and then point to the application server. The best way is to use location as a diversion, divert some requests that require session through ip_hash, and go to other backends for the rest.
5. upstream_hash
In order to solve some problems of ip_hash, you can use the third-party module upstream_hash. This module is used as url_hash in most cases, but it does not prevent it from being used for session sharing. I haven’t tried it before and I really don’t understand itSupplement: A brief introduction to memcached
1. Concept
Memcached is a distributed memory object caching system developed by danga.com (the technical team that operates LiveJournal) and is used in dynamic systems Reduce database load and improve performance.
2. Applicable occasions
1. Distributed applications. Since memcached itself is based on a distributed system, it is especially suitable for large distributed systems.
2. Database front-end cache. Databases are often the bottleneck of website systems. Large concurrent access to the database often causes website memory to overflow. Of course we can also use Hibernate's caching mechanism. However, memcached is based on distribution and can be independent of the website application itself, so it is more suitable for large websites to split applications.
3. Data sharing between servers. For example, we split the login system and query system of the website into two applications, place them on different servers, and cluster them. Then after the user logs in, how does the login information synchronize from the login system server to the query system server? Woolen cloth? At this time, we can use memcached. The login system caches the login information, and the query system can obtain the login information, just like obtaining local information.
3. Inapplicable occasions
For applications that do not need to be "distributed", do not need to be shared, or are simply small enough to have only one server, memcached will not bring any benefits. On the contrary, it will slow down the system efficiency. Because network connections also require resources
The solution is to use memcached as session storage, and the memcached server is set up on the same Linux host as nginx.
Solution process,
The host IPs of the two apache are 192.168.74.235192.168.74.236
The Nginx host IP is 192.168.74.131
The IP of the Memcached host is 192.168.74.131
Install memcached at 192.168.74.131, And start
Take one as an example 192.168.74.236, install php and php's dependency library on memcached yuminstall memcached-devel.i686 libmemcached-devel.i686 php-pecl-memcache.i686
Configure php.ini
session. save_handler= memcache
session.save_path= "tcp://192.168.74.131:11211"
Or (the following two have not been tried)
1. .htaccess in a certain directory:
php_value session.save_handler "memcache "
php_value session.save_path "tcp://IP:11211"2. In a certain application:
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://IP:11211");At the same time, be sure to comment out the following;session.save_path= "/var/lib/php/session"
At the same time, open extension=memcache.so
Restart apache, check "Registered save handlers" in phpinfo. There will be 3 "files usermemcache" available. If there are, it proves that it is installed.
Memcached server execution and results
[root@Git ~]# memcached-tool127.0.0 .1:11211
# Item_Size Max_age Pages Count Full? Evicted Evict_Time OOM
Add the following php file on the 236 machine
session_start();
if (!isset($_SESSION[' TEST'])) {
$_SESSION['TEST'] = time();
}
$_SESSION['TEST3'] = time();
print $_SESSION['TEST'];
print "
";print $_SESSION['TEST3'];
print "
";print session_id();
?>
Then go to the memcached server and execute
[root@Git ~]# memcached-tool127.0.0.1:11211
# Item_Size Max_age Pages Count Full? Evicted Evict_Time OOM
1 80B 0s 1 0 0 no 0 0 0
This should even allow the session to be written to the memcached server.
To summarize:
1. Firewall problem, many failures to connect to LAN servers are caused by firewalls
2. Dependencies have not been installed, and memcached always fails at the beginning because I have not installed an extension library like php-memcached
The above introduces how to solve the session sharing problem of nginx load balancing, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

Navicat itself does not store the database password, and can only retrieve the encrypted password. Solution: 1. Check the password manager; 2. Check Navicat's "Remember Password" function; 3. Reset the database password; 4. Contact the database administrator.

Create a database using Navicat Premium: Connect to the database server and enter the connection parameters. Right-click on the server and select Create Database. Enter the name of the new database and the specified character set and collation. Connect to the new database and create the table in the Object Browser. Right-click on the table and select Insert Data to insert the data.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

Steps to perform SQL in Navicat: Connect to the database. Create a SQL Editor window. Write SQL queries or scripts. Click the Run button to execute a query or script. View the results (if the query is executed).

Common reasons why Navicat cannot connect to the database and its solutions: 1. Check the server's running status; 2. Check the connection information; 3. Adjust the firewall settings; 4. Configure remote access; 5. Troubleshoot network problems; 6. Check permissions; 7. Ensure version compatibility; 8. Troubleshoot other possibilities.

You can create a new MySQL connection in Navicat by following the steps: Open the application and select New Connection (Ctrl N). Select "MySQL" as the connection type. Enter the hostname/IP address, port, username, and password. (Optional) Configure advanced options. Save the connection and enter the connection name.

Common errors and solutions when connecting to databases: Username or password (Error 1045) Firewall blocks connection (Error 2003) Connection timeout (Error 10060) Unable to use socket connection (Error 1042) SSL connection error (Error 10055) Too many connection attempts result in the host being blocked (Error 1129) Database does not exist (Error 1049) No permission to connect to database (Error 1000)
