How Memcached works
In the following sections, you are advised to prepare the source code of memcached.
Memcached is a traditional network service program. If the-d parameter is used during startup, it will be executed as a daemon process. Daemon. c is used to create daemon. This program has only one daemon function. This function is very simple (unless otherwise stated, the code is subject to 1.2.1 ):
The code is as follows: |
Copy code |
CODE: # Include <fcntl. h> # Include <stdlib. h> # Include <unistd. h> Int Daemon (nochdir, noclose) Int nochdir, noclose; { Int fd; Switch (fork ()){ Case-1: Return (-1 ); Case 0: Break; Default: _ Exit (0 ); } If (setsid () =-1) Return (-1 ); If (! Nochdir) (Void) chdir ("/"); If (! Noclose & (fd = open ("/dev/null", O_RDWR, 0 ))! =-1 ){ (Void) dup2 (fd, STDIN_FILENO ); (Void) dup2 (fd, STDOUT_FILENO ); (Void) dup2 (fd, STDERR_FILENO ); If (fd> STDERR_FILENO) (Void) close (fd ); } Return (0 ); } |
After this function fork the entire process, the parent process will exit, and then relocates STDIN, STDOUT, and STDERR to the empty device, and daemon will be established successfully.
The code is as follows: |
Copy code |
<? Php Class Memcached { Private $ mem; Public $ pflag = ''; // memcached pconnect tag Private function memConnect ($ serkey ){ Require 'config. Php '; $ Server = $ memcached; $ This-> mem = new Memcache; $ Link =! $ This-> pflag? 'Connect ': 'pconnect '; $ This-> mem-> $ link ($ server [$ serkey] [0], $ server [$ serkey] [1]) or $ this-> errordie ('memcached connect error '); } Public function set ($ ser_key, $ values, $ flag = '', $ expire = ''){ $ This-> memConnect ($ this-> tag ($ ser_key )); If ($ this-> mem-> set ($ ser_key, $ values, $ flag, $ expire) return true; Else return false; } Public function get ($ ser_key ){ $ This-> memConnect ($ this-> tag ($ ser_key )); If ($ var = $ this-> mem-> get ($ ser_key) return $ var; Else return false; } Private function tag ($ ser_key ){ $ Tag = explode ('_', $ ser_key ); Return $ tag [0]; } Private function errordie ($ errmsg ){ Die ($ errmsg ); } } ?> |
The code is as follows: |
Copy code |
Class Mysql { Private $ mysqlmaster; Private $ myssqlslave; Private static $ auid = 0; Public function _ construct (){ Require 'config. Php '; $ Msg = $ mysql;
$ This-> mysqlmaster = new mysqli ($ msg ['master'] [0], $ msg ['master'] [1], $ msg ['master'] [2], $ msg ['master'] [3]); // master mysql $ This-> mysqlslave = $ this-> autotranscat ($ msg); // slave mysql If (mysqli_connect_errno ()){ Printf ("Connect failed: % s", mysqli_connect_error ()); Exit (); } If (! $ This-> mysqlmaster-> set_charset ("latin1 ")&&! $ This-> mysqlslave-> set_charset ("latin1 ")){ Exit ("set charset error "); } } Private function autotranscat ($ mysql ){ Session_start (); $ _ SESSION ['Sid ']! = 0 | $ _ SESSION ['Sid '] = 0; If ($ _ SESSION ['Sid ']> = count ($ mysql)-1) $ _ SESSION ['Sid'] = 1; Else $ _ SESSION ['Sid '] ++; $ Key = 'slave _ '. $ _ SESSION ['Sid']; Echo ($ _ SESSION ['Sid ']); Return new mysqli ($ mysql [$ key] [0], $ mysql [$ key] [1], $ mysql [$ key] [2], $ mysql [$ key] [3]); } Public function mquery ($ SQL) {// insert update If (! $ This-> mysqlmaster-> query ($ SQL )){ Return false; } } Public function squery ($ SQL ){ If ($ result = $ this-> mysqlslave-> query ($ SQL )){ Return $ result; } Else { Return false; }; } Public function fetArray ($ SQL ){ If ($ result = $ this-> squery ($ SQL )){ While ($ row = $ result-> fetch_array (MYSQLI_ASSOC )){ $ Resultraa [] = $ row; }; Return $ resultraa; } } } ?> Require 'init. Php '; $ Mem = new Memcached; /* $ Mem-> set ('en _ xx', 'bucuo '); Echo ($ mem-> get ('en _ xx ')); $ Mem-> set ('CN _ jjyy ', 'wokao '); Echo ($ mem-> get ('CN _ jjyy ')); */ $ Sq = new Mysql; $ SQL = "insert into mybb (pid) values (200 )"; $ Mdsql = md5 ($ SQL ); If (! $ Result = $ mem-> get ('CN _ '. $ mdsql )){ $ Sq-> mquery ("insert into mybb (pid) values (200)"); // insert to primary mysql $ Result = $ sq-> fetArray ("select * from mybb"); // The query is from mysql Foreach ($ result as $ var ){ Echo $ var ['pid']; } $ Mem-> set ('CN _ '. $ mdsql, $ result); // add it to the memcached server named cn. } Else { Foreach ($ result as $ var ){ Echo $ var ['pid']; } } ?> |
The code is as follows: |
Copy code |
<? Php $ Memcached = array (// use the memcached multi-process to simulate multiple memcached servers. The cn en is the name of the memory server. 'Cn' => array ('192. 168.254.144 ', 192 ), 'En' => array ('192. 168.254.144 ', 192) ); $ Mysql = array (// mysql master/slave my environment is: xp master linux from mysql 5 php5 'Master' => array ('192. 168.254.213 ', 'root', '1', 'mydz '), 'Slave _ 1' => array ('192. 168.254.144 ', 'root', '1', 'mydz') // You can flexibly add multiple slave servers. ); ?> |
The starting process of Memcached itself is as follows in the main function of memcached. c:
1. Call settings_init () to set initialization parameters.
2. Read the parameter from the startup command to set the setting value.
3. Set the LIMIT parameter.
4. Start network socket listening (if a non-socketpath exists) (UDP is supported after 1.2)
5. Check the user identity (Memcached does not allow root startup)
6. If socketpath exists, enable the UNIX local connection (Sock pipeline)
7. If the daemon is started in the-d mode, create a daemon process (call the daemon function above)
8. Initialize item, event, status information, hash, connection, and slab.
9. If managed takes effect in the settings, create a bucket array.
10. Check whether the memory page needs to be locked.
11. Initialize signals, connect and delete queues
12. If the daemon method is used, process the process ID
13. Start event and start process. The main function enters the loop.
In the daemon mode, stderr has been redirected to a black hole, so no visible error information is reported during execution.
The main cyclic function of memcached. c is drive_machine. The input parameter is the structure pointer to the current connection. The action is determined based on the state of the state member.
Memcached uses a set of custom protocols for data exchange, its protocol documentation can refer to: http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt
In API, the line feed symbol is