Synchronization-how does PHP implement SESSION sharing for multiple servers?

Source: Internet
Author: User
Tags redis cluster
Question: {code ...} answer: {code ...} q: {code ...} this is an interview question. When I answered the question of using a database to store sessions, the interviewer was not satisfied. My own idea was to think about how to share sessions for multiple sub-stations, such as top-level domains and multi-subdomains. So... question:

How can I share sessions with multiple servers?

Answer:

The solution saves the SESSION to the database. Different Hosts can read the SESSION database to determine whether to log on online.

Q:

How can I ensure that the SESSION can be read Normally when a large number of concurrent accesses occur?

This is an interview question. When I answered the question of using a database to store sessions, the interviewer was not satisfied. My own idea was to think about how to share sessions for multiple sub-stations, such as top-level domains and multi-subdomains. For the convenience of synchronization, I think of database storage. But how can I handle high concurrency? (Abandon database storage SESSION for other solutions ?)

Reply content:

Question:

How can I share sessions with multiple servers?

Answer:

The solution saves the SESSION to the database. Different Hosts can read the SESSION database to determine whether to log on online.

Q:

How can I ensure that the SESSION can be read Normally when a large number of concurrent accesses occur?

This is an interview question. When I answered the question of using a database to store sessions, the interviewer was not satisfied. My own idea was to think about how to share sessions for multiple sub-stations, such as top-level domains and multi-subdomains. For the convenience of synchronization, I think of database storage. But how can I handle high concurrency? (Abandon database storage SESSION for other solutions ?)

If you want to save MySQL, the interviewer will ask what to do with high concurrency, which means that it is not recommended to store MySQL. In this case, you have to answer: Save Redis or Memcached.

If I am an interviewer, I will ask again. What should I do if a single Redis instance cannot be put down due to a large number of users? It also indicates that it is not feasible to store all sessions on a single machine. There are two methods: Method 1: the server does not save the Session, and the user's Session (note: not only the SessionID) is stored locally (using Cookie or LocalData ), however, there are several serious problems: security, the amount of data transmitted over http, and the upper limit of local storage. Also, this is not a Session, but a Cookie solution.
Method 2: server-side distributed storage (Redis cluster and Memcached cluster). Since it is distributed, you must ensure that each request reaches the specified server, because his Session is on the specified Shard, the flag can be in the Cookie of the user, when the user requests, the server sends the request Route to the specified shard Based on the content in the Cookie.

If you answer the question in this way, I will ask again, what should I do if a part fails, then all the user sessions will be lost. This is highly available. Multiple replica sets (slave nodes) are created for each shard. When the master shard crashes, the slave node continues to provide access.

Well, this is basically the theory of distributed systems.

Use MySQL to store user session information
Database-based session implementation:
Login User:
Online1 (sessid, session, time, version); $ _ COOKIE ['myid'] content: User ID (as sessid) + password hash (verify identity)
Common Visitor:
Online2 (sessid, session, time, version); $ _ COOKIE ['myid'] content: User ID (0) + session ID (sessid)

Sessid is the user ID, and the visitor is the ID generated by online_id () when it is a common visitor.
Session stores user sessions. The content is the serialized string of the session array serialize.
Time is the Record Update time.
Version is the version number, used to implement the CAS (Check And Set) optimistic lock, to ensure the session field data consistency.

Unique visitor ID generation function:

function online_id(){$time = !empty($_SERVER['REQUEST_TIME_FLOAT']) ? $_SERVER['REQUEST_TIME_FLOAT'] : mt_rand();$addr = !empty($_SERVER['REMOTE_ADDR'])        ? $_SERVER['REMOTE_ADDR']        : mt_rand();$port = !empty($_SERVER['REMOTE_PORT'])        ? $_SERVER['REMOTE_PORT']        : mt_rand();$ua   = !empty($_SERVER['HTTP_USER_AGENT'])    ? $_SERVER['HTTP_USER_AGENT']    : mt_rand();return md5(uniqid(mt_rand(), true).$time.$addr.$port.$ua.mt_rand());}

Table Structure:

CREATE TABLE `online1` (`sessid` int(10) unsigned NOT NULL DEFAULT '0',`session` varchar(20000) NOT NULL DEFAULT '',`time` int(10) unsigned NOT NULL DEFAULT '0',`version` int(10) unsigned NOT NULL DEFAULT '0',PRIMARY KEY (`sessid`),KEY (`time`),KEY (`version`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;CREATE TABLE `online2` (`sessid` char(32) NOT NULL DEFAULT '',`session` varchar(20000) NOT NULL DEFAULT '',`time` int(10) unsigned NOT NULL DEFAULT '0',`version` int(10) unsigned NOT NULL DEFAULT '0',PRIMARY KEY (`sessid`),KEY (`time`),KEY (`version`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

Read/write functions:

function cn_session_get($sessid) { CRUD($_COOKIE['myid'],online1,online2) + return unserialize($session); }function cn_session_set($sessid,$session) { serialize($session) + CURD_CAS_UPDATE }

Function call:

$ Session = cn_session_get ($ sessid); print_r ($ session ['cart']); $ session ['cart'] = array (); cn_session_set ($ sessid, $ session); or register_shutdown_function (cn_session_set, $ sessid, $ session );

CnSessionWhen set () is used, the version number is used for conflict detection to ensure the consistency of session field data:

cn_session_get: SELECT * FROM online WHERE sessid=1;cn_session_set: UPDATE online SET session=$session,version=last_version+1 WHERE id=1 AND version=last_version;

If no update record exists, a message indicating AJAX operation failure is returned.

Comparison: PHP's built-in session mechanism uses the exclusive lock (pessimistic lock ).
SessionStart () enables a pair of sessID: The write protection lock of the session file,
Operate on the same sess on other pagesID: session of the session FileStart () will be blocked,
Until the request is completed or the session is usedWriteClose () explicitly closes.
This SESSION lock mechanism avoids the following situations:
Page A and page B read the same session information.
The session variable A is modified and written to page.
Page B is subsequently modified and written to session variable B.
At this time, page B will overwrite the session variable A written on page.
Note: This kind of concurrency rarely occurs. Therefore, it is reasonable to use optimistic locks based on the database-implemented session mechanism, without frequent operation failures.
Session Application Scenario: record user information after logon, shopping cart (Read/Add/delete), viewing record, verification code, csrf_token.
Saving the shopping cart data in serialized or JSON strings to database fields will lead to the loss of the SQL query function.
If the shopping cart is stored in the form of database records, it is convenient for SQL query and analysis.
Since SQL has been abandoned, You can naturally use NoSQL, such as Memcached/Redis, to design a solution similar to the above MySQL.

@ Eechen describes how to use custom session storage between multiple nodes under a single node or the same primary domain name. In fact, php itself has the function of saving external storage, you can see this tutorial: http://www.sitepoint.com/saving-php-sessions-in-redis. For all web sites, session Background storage is the same redis, so even if the web site is scheduled to any node, the session data read remains unchanged.
I don't know if the interviewer is asking if the session is shared by different primary domains. If so, this solution cannot be used.

A consistent hash is implemented for client signs such as sessionid to ensure that each access to the same machine is performed. For n clients, the function of praying for traffic distribution does not work.
It's really hard to figure out what the examiner asks and give a "correct" answer.

Indeed, redis and memcache are the best choice, because they are memory databases and hard disk databases are the bottleneck of Hard Disk Io. Redis is recommended between the two because it supports many data formats and is highly scalable, such as persistence.

Use memcached.

Session is not persistent storage, but it is quite different from rdbs, but it is similar to memcached.

The sessionid can be replaced by the uid in the application and needs to be manually managed.

Memcache is the best choice to use memcache to implement the session function.

Redis can be stored.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.