PHP memcached MySQL Development detailed example _php tutorial

Source: Internet
Author: User
Tags mysql tutorial pconnect php memcached
PHP tutorial memcached MySQL Tutorial development detailed examples

How the memcached works

In the following sections, it is best to prepare a copy of the memcached source code.

Memcached is a traditional network service program, and if you use the-D parameter when you start it, it executes as a daemon. The creation daemon is done by DAEMON.C, which has only one daemon function, which is very simple (if no special instructions, the Code is 1.2.1):

CODE:
#include
#include
#include

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 the function has forked the entire process, the parent process exits, then the STDIN, STDOUT, STDERR to the empty device are relocated, and the daemon is established successfully.

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);
}
}
?>


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:%sn", 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 main MySQL
$result = $sq->fetarray ("SELECT * from MyBB"); Query is from MySQL
foreach ($result as $var) {
echo $var [' pid '];
}
$mem->set (' Cn_ ' $mdsql, $result); Add to memcached server named CN
}else{
foreach ($result as $var) {
echo $var [' pid '];
}
}
?>

$memcached = Array (//multi-process simulation with memcached multiple memcached server cn en as Memory server name
' CN ' =>array (' 192.168.254.144 ', 11211),
' En ' =>array (' 192.168.254.144 ', 11212)
);
$mysql = Array (//MySQL master-slave My environment is: XP main Linux from MySQL 5 php5
' Master ' =>array (' 192.168.254.213 ', ' root ', ' 1 ', ' Mydz '),
' Slave_1 ' =>array (' 192.168.254.144 ', ' root ', ' 1 ', ' mydz ')//flexibility to add multiple slave servers
);
?>

The Memcached itself starts with the following sequence in the main function of MEMCACHED.C:

1. Call Settings_init () to set initialization parameters
2. Set the setting value by reading the parameters from the start command
3. Set LIMIT parameter
4. Start Network socket Monitoring (if non-socketpath exists) (UDP is supported after 1.2)
5, check the user identity (Memcached not allow ROOT to start)
6. If a socketpath exists, open UNIX Local connection (Sock pipeline)
7. If you start with-D, create a daemon (call the daemon function above)
8. Initialize item, event, status information, hash, connection, slab
9. Create bucket array If managed is active in Settings
10. Check if you need to lock memory pages
11. Initialize signal, connect, delete queue
12, if the daemon way, processing process ID
13, the event starts, the START process ends, the main function enters the loop.

In daemon mode, because stderr has been directed to a black hole, there is no feedback on the visible error message in the execution.

The main loop function of the MEMCACHED.C is Drive_machine, which is the structure pointer to the current connection, and determines the action based on the state of its member.

Memcached uses a set of custom protocols to complete the exchange of data, its protocol documentation can be consulted: http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

In the API, the line break symbol is unified as RN


http://www.bkjia.com/PHPjc/444946.html www.bkjia.com true http://www.bkjia.com/PHPjc/444946.html techarticle php tutorial memcached mysql Tutorial Developing a detailed example of how memcached works in the following sections, it is a good idea for readers to prepare a copy of the memcached source code. Memcached is a traditional network service ...

  • 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.