Memcached general application and distributed deployment scheme

Source: Internet
Author: User
Tags md5 memcached ord

1, memcached general application

$MC=NewMemcache ();$MC->conncet (' 127.0.0.1 ', 11211);$sql=sprintf("SELECT * from users WHERE uid =%d",$_get[' UID ']);$key=MD5($sql);//whether the test results have been cachedif( !$data=$MC->get ($key)){    //no cache is read directly from the databaseMysql_conncet (' localhost ', ' test ', ' test '); mysql_select_db(' Test ');  while($row=Mysql_fetch_object(mysql_query($sql))){        $data[] =$row; }    //and cache the query results    $MC->add ($key,$data);}Var_dump($data);

Note: first through MD5 () the SQL statement into a unique key, and this key query memcached detection is cached, if the result is returned directly, otherwise query the database before caching, and return the results. This way, the next time you use this key, you can return the results directly.

2, memcached distributed deployment scenarios, for multiple memcached servers, how to determine the data should be saved to which server? There are two schemes, one is the normal hash distribution, the other is the consistent hash distribution. Detailed instructions below.

Scenario One: Simple modulo operation

<?PHP//hash FunctionfunctionMhash ($key){    $MD 5=substr(MD5($key), 0, 8); $seed= 31; $hash= 0;  for($i= 0;$i< 8;$i++){        $hash=$hash*$seed+Ord($MD 5{$i}); $i++; }    return $hash& 0x7FFFFFFF;}//Suppose there are 2 memcached servers$servers=Array(    Array(' host ' = ' 192.168.1.1 ', ' port ' = 11211),Array(' host ' = ' 192.168.1.1 ', ' port ' = 11211));$key= ' MyBlog ';$value= ' Http://www.cnblogs.com/gide ';$SC=$servers[Mhash ($key)% 2];$memcached=NewMemcached ($SC);$memcached->set ($key,$value);

Note: First, the key is processed into a 32-bit string by the MD5 function, then the first 8 bits are truncated, and then the hash algorithm is processed into an integer and returned. Using this integer and the number of memcached servers to determine which memcached server the current key is stored in, the memcached distributed deployment is completed. It is conceivable that when you want to read the value of key, it is still the hash algorithm to determine which server to store

Scenario Two: Consistent hash deployment

<?PHPclassflexihash{//Server List    Private $serverList=Array(); //whether the record has been sorted    Private $isSorted=FALSE; //Add a server     Public functionAddserver ($server){        $hash=$this->mhash ($server); if(!isset($this->serverlist[$hash])){            $this->serverlist[$hash] =$server; }        //need to re-order        $this->issorted =FALSE; return TRUE; }    //Removing a server     Public functionRemoveserver ($server){        $hash=$this->mhash ($server); if(isset($this->serverlist[$hash])){            unset($this->serverlist[$hash]); }        //need to re-order        $this->issorted =FALSE; return TRUE; }    //find the right server in the current server list     Public functionLookup$key){        $hash=$this->mhash ($key); //Reverse sort operation First        if(!$this-issorted) {            Krsort($this->serverlist,sort_numeric); $this->issorted =TRUE; }        //find a server near the current key in a clockwise direction on the ring        foreach($this->serverlist as $pos=$server){            if($hash>=$pos)return $server; }        //the last server is returned in a clockwise direction without being found        return $this->serverlist[Count($this->serverlist)-1]; }    //hash Function    Private functionMhash ($key){        $MD 5=substr(MD5($key), 0, 8); $seed= 31; $hash= 0;  for($i= 0;$i< 8;$i++){            $hash=$hash*$seed+Ord($MD 5{$i}); $i++; }        return $hash& 0x7FFFFFFF; }}?>

Description: The consistent hash distribution algorithm is divided into 4 steps:
Step 1: Think of a 32-bit integer [0 ~ (2^32-1)] as a ring, 0 as the beginning, (2^32-1) as the end, of course, this is just imagination.
Step 2: The key is processed into integers through the hash function. This allows you to find a location on the ring that corresponds to it.
Step 3: Map the memcached server farm to the ring, using the hash function to process the server corresponding IP address.
Step 4: Map the data to the memcached server. Here's how to find the memcached server location for a key: from the position of the current key, go clockwise along the circle, find the nearest memcached server, and save the data for the key to this server.

Specific application:

<?PHP$hserver=NewFlexihash ();//Initial 5 Servers$hserver->addserver ("192.168.1.1");$hserver->addserver ("192.168.1.2");$hserver->addserver ("192.168.1.3");$hserver->addserver ("192.168.1.4");$hserver->addserver ("192.168.1.5");Echo"Save Key1 in Server:",$hserver->lookup (' Key1 '), "<br/>";Echo"Save Key2 in Server:",$hserver->lookup (' Key2 '), "<br/>";Echo' ===============================================<br/> ';//removing 1 servers$hserver->removeserver ("192.168.1.4");Echo"Save Key1 in Server:",$hserver->lookup (' Key1 '), "<br/>";Echo"Save Key2 in Server:",$hserver->lookup (' Key2 '), "<br/>";Echo' ===============================================<br/> ';//Add 1 Servers$hserver->addserver (' 192.168.1.6 ');Echo"Save Key1 in Server:",$hserver->lookup (' Key1 '), "<br/>";Echo"Save Key2 in Server:",$hserver->lookup (' Key2 ');?>//The test results are as follows:Save Key1 in server:192.168.1.4save Key2 in Server: 192.168.1.2==================================save Key1 in Server: 192.168.1.3save Key2 in Server: 192.168.1.2==================================save Key1 in Server: 192.168.1.3save Key2 in Server: 192.168.1.2

But Memcached brought his own addserver.

memcached::addserver-adding a server to the server pool
public bool Memcached::addserver (string $host, int $port [, int $weight = 0])
Host
Memcached Server host name. If the hostname is invalid, the return code for the associated data operation is set to Memcached::res_host_lookup_failure.

Port
The Memcached service port number, usually 11211.

Weight
The weight of this server relative to all servers in the server pool. This parameter is used to control the probability that the server is being seed-selective during operation. This is used only for the consistency distribution option, and this value is usually set by the memory allocated by the server.

Returns TRUE on success, or FALSE on failure.

<? PHP $m New Memcached (); $m->addserver (' mem1.domain.com ', 11211,); $m->addserver (' mem2.domain.com ', 11211, 67);

Complete!

Memcached general application and distributed deployment scheme

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.