How to Use PHP+REDIS to Solve session Sharing Problem after Load Balancing

  load balancing, session

First, why use Session sharing?

For larger websites, there are usually several servers. Each server runs modules with different functions and uses different secondary domain names. For a website with strong integrity, the user system is unified, i.e. a set of user names and passwords can be logged in and used in each module of the entire website. It is relatively easy for each server to share user data. Only a database server needs to be placed at the back end, and each server can access user data through a unified interface. However, there is still a problem that users still need to log in again when entering other modules of another server after logging in to this server. This is the problem of one login and all traffic. Mapping to technology is actually the problem of how to share SESSION data among servers.

Second, understand the working principle of session

Before solving the problem, let’s understand how PHP SESSION works. When the client (e.g. browser) logs in to the website, the accessed PHP page can use SESSION_start () to open the session, which will generate the unique IDentification SESSION ID of the client (this id can be obtained/set through the function session_id (). SESSION ID can be kept in the client in two ways, so that PHP program can know the session ID of the client when requesting different pages. One is to automatically add SESSION ID to the URL of GET or the form of POST. by default, the variable name is PHPSESSID;. The other is to save the SESSION ID in the COOKIE through the COOKIE. by default, the name of this COOKIE is PHPSESSID. Here we mainly explain it by COOKIE, because it is widely used.

The server distinguishes users by session_id passed by the client, which is used to mark the user’s login status.

When the user sends the request again, the session_id returned by the server is transferred to the server through cookie[ or URL transfer parameter], so that the server can distinguish the users of specific operations.

Three, how to solve the problem of session sharing after load balancing?

1. Do not use the session and replace it with a cookie.

Changing the session into a cookie can avoid some disadvantages of the session. [Low Safety]

2. The database records session information

The use of database to record session information is relatively frequent. If there is a database, frequent reading will exert great pressure on the database, and the bottleneck of website performance generally exists in the database.

3. Use ip_hash algorithm for distribution when load balancing

Using ip_hash may result in a heavy load on one server. If the server enters many requests from fixed IP agents within a certain period of time [over the wall, agents], if the load of the agent IP is too high, the load pressure of the server corresponding to ip_hash will be too high, thus ip_hash will lose its load balancing function.

4. Synchronize the session file

Using the synchronization tool to synchronize the session files ensures that the session files of the load servers are consistent. Although this method can solve the problem of session sharing, the same content will exist on multiple servers, and the session files existing in some servers may not be used at all from the beginning to the end, wasting the resources of the servers. “rsync, inotify-tools, etc.”

5. Use memcache or redis to save session information [Suggestion]

Compared with retrieving information from files, retrieving data from memory is much faster, and it is more convenient when multiple servers need to share a session. It is only necessary to configure these servers to use the same set of memcached servers, thus reducing the extra workload. The disadvantage is that the session data is stored in memory, and once it goes down, the data will be lost. But it is not a serious problem for session data.

4. PHP+REDIS to Solve session Sharing Problem

1. session default storage is configured in php.ini

session.save_handler = files  
//session保存路径  N表示按照分级存储
session.save_path = "N;/path"

Note: session.save_path = “2; /data/session_tmp “means that the session file is stored in two levels, i.e./data/session _ tmp/4/b/ses _ 4b1e384 ad74619bd212e236e52a5a174if, taking the first two characters, but php does not generate directories and needs to generate them manually.

session.save_path = "d:/wamp/tmp"    php自带函数session_save_path
session.auto_start = 0

2. Set the session saving method as redis

(1) Restart php-fpm and nginx to change php.ini configuration file after modification

session.save_handler = redis
        session.save_path = “tcp://″

(2) set via ini_set


Password setting


(3) concrete realization

 //ini_set('session.save_handler', 'redis');       
  //ini_set('session.save_path', 'tcp://');      
    $_SESSION['sessionid'] = 'this is session content!';        
    echo $_SESSION['sessionid'];       
     echo '<br/>';
        $redis = new redis();       
         $redis->connect('', 6379);       
          $redis->auth( ‘redisauthkey’ );
echo $redis->get('PHPREDIS_SESSION:' . session_id());  

3. establish your own session mechanism through session_id

With the help of session_id, a set of its own mechanism is suggested. The principle can be referred to the session preservation mechanism.

  • When the user requests for the first time, issue session_id to the user.
  • After that, all requests must be brought to the session.
  • After the user logs in, the user information is stored in redis, which is represented by session_id.

The advantage is: abstract one’s own session mechanism as a class. If there is no redis in the later session, the problem can be solved directly by modifying the class file.

Author: Qi Yawei

Source:Yixin Institute of Technology

Expand reading:Data in Taiwan: Construction Practice of Yixin Agile Data in Taiwan | Record of Sharing