Use Memcached for Session sharing

Application scenarios

When there are many users, the login location of these users is on different servers, because sessions are generated on the server. When users visit each other, sometimes they find that they have permissions, sometimes they find that they do not. Since the cache is centralized and all caches are in one place, you can place your session in the memcached cache. All servers can fetch sessions from a common server, so that no matter which server the user logs in to, they will have the correct session. This has two advantages. First, it solves the problem of session sharing. Second, when there are a large number of users, sessions are stored on the server, thus increasing disk IO, but if they are stored in the cache, the nature is completely different.

implementation

  • Set up the php.ini configuration file

Vim/etc/PHP / 7.2 / FPM/PHP ini

  1. Change Seesion storage to memcached

By default PHP stores sessions as files

1337 session.save_handler = files

So you need to change it to memcached

session.save_handler = "memcached"
  1. Modify the session location

The default PHP comment is out

1366 ;session.save_path = "/var/lib/php/sessions"

Modified to

Note: 192.168.174.128 is the IP address of my virtual machine. I need to change this to the IP address of your memcached server

# For PHP 5.6 and below, Need to be written in the following session. Save_path = "TCP: / / 192.168.174.128:11211 # 7 above for PHP can be directly into the session. Save_path =" 192.168.174.128:11211"
  • If you only want to fetch a single PHP file from the cache when fetching a session, you can set this as follows

vim test.php

<? php ini_set("session.save_hander", "memcached"); Ini_set (" session. Save_path ", "192.168.174.128:11211");
  • You can also use Apache or Nginx Settings

Disadvantages of putting sessions in memcached:

Cluster errors can cause users to be unable to log in, and memcached’s recycling mechanism can cause users to drop out

The original address