YII2-PHP session memcache cluster configuration scheme

Posted May 28, 20202 min read


Because a memcache service has always been used for the session of the online PHP cluster, the service response requests often have a large standard deviation. The same request will not occur in theory. The final positioning is a problem caused by a single memcache .


Try to simulate memcached multi-port with docker on a single machine in the test environment, and use multiple browsers to simulate requests on the client side, and test the feasibility of php service configuration session-memcached cluster for offloading.


Docker configure memcache cluster

Install docker and pull the memcached public image(this step is Google Baidu). image.png

Start 3 memcached instances:

docker run --name my-memcache -p 11210:11211 -d memcached:1.5.16
docker run --name my-memcache-20 -p 11220:11211 -d memcached:1.5.16
docker run --name my-memcache-30 -p 11230:11211 -d memcached:1.5.16

Run docker ps to check the startup status:

PHP-INI configuration session

The memcached extension needs to be installed first. The bottom layer of PHP will combine memcached to automatically distribute the request. Check the official memcached documentation. Memcached is distributed by the client. I used to think that the business layer needs to be consistent. In fact, this That's wrong, php's memcached extension has long encapsulated and implemented this function for the business layer. For this, we configure 3 test nodes(11210, 11220, 11230)


Open 3 ssh terminals and check the data of each port of memcache
Enter memcache

telnet 11210

Several tests have been done, one of which fell into one, and the data will randomly fall on the other two.

Of course, this is not the only solution. Common frameworks will use PHP's session handler, which can be implemented by client code without modifying the configuration in php \ _ini. Under the YII2 framework,
The default components can be configured:

        'session' => [
            'class' => 'yii \ web \ Session',
            'name' => 'newrent-frontend-session',
            'timeout' => 3600 * 24,
            'cookieParams' => [
                'path' => '/',
                'domain' => ".xxx.com",

Can also be implemented with redis components

to sum up

It can be seen that the memcached-session cluster of users of different browsers has completed the distribution. After the browser client obtains the sessionid, subsequent requests after this can ensure normal access, and this solution can solve a single The performance problem of session-memcache.