Using memcache to realize synchronous session of session in web cluster

  • 2021-07-06 10:33:53
  • OfStack

It is good to use memcache to synchronize session. Of course, session can be saved by redis, php can be opened and Session can be stored in Redis cache. The following is the implementation process of setting up the synchronization session session in web cluster by using memcache:

1. Simulate web cluster

I started two memcached processes, simulating two servers each

/usr/local/bin/memcached -d -m 20 -u zhangy -p 12000 -P ./memcached.pid
/usr/local/bin/memcached -d -m 20 -u zhangy -p 13000 -P ./mem.pid

2. Modify the configuration of php

vi /usr/local/php/lib/php.ini

session.save_handler = "memcache"
memcache.hash_strategy = "consistent"
session.save_path = "tcp://127.0.0.1:13000?weight=10,tcp://127.0.0.1:12000"

Note: In line 1, the storage mode of session is memcache;; In line 2, the hash algorithm of memcache is consistent; Line 3, the status of session storage;

3. Restart apache

View phpinfo

session

Session Support enabled
Registered save handlers files user sqlite memcache
Registered serializer handlers php php_binary

Immediately below are:

session.save_path tcp://127.0.0.1:13000,tcp://127.0.0.1:12000 tcp://127.0.0.1:13000,tcp://127.0.0.1:12000

4. Do a simple test as follows:

a), prepare the file session. php


<?php 
session_start(); 
$_SESSION['username'] = "abcabc"; 
echo session_id(); 
?>

b), which displays the session content file


<?php 
$mem = new Memcache; 
$mem->addServer("127.0.0.1",12000)or die ("Could not add server 12000"); 
$mem->addServer("127.0.0.1",13000)or die ("Could not add server 13000"); 
$val = $mem->get('qp0mrob2ovcqle3u4lbr4obsa5'); 
//echo session_id();  Get session id
echo $val; 
?>


Related articles: