It is good to use memcache to synchronize the session. Of course, you can also save the session through redis. You can open it with php and store the session in the Redis cache. The following is the implementation process of setting up using memcache to synchronize the session session in the web cluster:
1. Simulate web cluster
I started two memcached processes to simulate two servers respectively
/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"
Explanation: The first line, the storage method of session is memcache; the second line, the hash algorithm of memcache is consistent; the third line, the location 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 |
The following is:
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), display 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(); 得到的session id echo $val; ?>