PHP memcache and memcached

Source: Internet
Author: User
Tags php website

This article introduces you to PHP memcache and memcached, interested friends can see

**memcache Introduction: **memcache is a set of distributed cache system, distributed means can be installed on multiple servers at the same time Memcache services, which can achieve a good cluster effect. High speed, because the memcache data is maintained in memory, it reads faster than the data stored on the hard disk.
role: When our application access is relatively large, the database pressure is also very large, memcache can add a buffer layer between the application and the database, which is the data we have read from the database, the second or next time we read it, You can directly access the Memcache to read this data, thus reducing the pressure of MySQL and so on database
How to Memcache: In fact, it can be understood, it is a database with only one table, this table has two fields, respectively, key and Value,value are saved data, key is the ID of this data, to ensure the uniqueness of the search
Usage Scenarios:
(1) Non-persistent storage: The data storage requirements are not high, that is, if the data is lost, it will not be too much impact on the system, because when the system is powered off or restarted after the memory will be emptied, then the data saved in the memcache will be erased. So use memcache as a cache instead of a real database.
(2) Distributed storage: not suitable for single use, because Memcache memory consumption is very large, if using memcache, it is recommended to install it on a separate machine as a cache system, rather than the memcache and the database are loaded into a machine.
(3) Key/value storage: Simple format, does not support list, array data format

Memcached and Memcache are two versions, recommended memcached, it has more improvements and functional functions, is memcache upgrade version, speed and stability are higher

Installing memcached
1,memcache installation of the service side
(1) Compile and install, Libevent Memcache
Install libevent This extension, the advantage of compiling and installing is that you can make some custom settings during the installation, such as specifying where the software is installed, such as what errors have occurred during the compilation and installation process, and if you do not know much about Linux, you may be more difficult to handle errors
(2) Install using the Dependency management tool yum, Apt-get

Actual installation: (the operating system is 64-bit CentOS)
If you want to compile the installation, you need to download the installation package in advance libevent, memcached
This is installed using the dependency management tool

#yum Install memcached

Start memcached

#/usr/bin/memcached-d-L 127.0.0.1-p 11211-m 150-u root/*    -D: Daemon mode starts. The daemon is that when you launch from the terminal window, the program still    does the-l: Specify the IP address    -P: Specify the port number-    m: How much memory is allocated for memcached, here is the M-    u: in which identity to start memcached (It is best not to use the Super Admin user on the line) */

You can use PS to see if the memcached process is started

#ps-ef | grep memcached

installation of the 2,memcache client
1, install the pre-extension libmemcached
Download good libmemcached and memcached, unzip the libmemcached
Here to use the compiled installation, into the extracted folder
Perform

#./configure--prefix=/usr/lib/libmemcached then executes #make && Makeinstall

2, install memcached Extension for PHP
Unzip the memcached and go to the unzip directory
Installing the memcached extension using the Phpize method

#phpize此时就会做出一个configure的文件 #./configure--with-php-config=/usr/local/php/bin/php-config--with-libmemcached-dir= /USR/LIB/LIBMEMCACHED-SASL behind is the specified PHP configuration file and the location of the newly installed libmemcached, everyone according to their own configuration file path to fill #make#make install after you execute make install , we will see an extension directory, add the path to the PHP configuration file php.ini and then restart the server environment to see the PHP extension #php-m | grep memecached

Using memcached in PHP
System classes:addserver, Addservers, GetStats, getversion
Data classes: Add,set,delete, flush, replace, increment,get
Advanced classes: Setmulti, Deletemulti, Getmulti, Getresultcode, Getresultmessage
More about memecached, can be viewed on the PHP website (php.net)

test.php<?php/* System class */$m = new Memcached ();/* Add server */$m->addserver (' 127.0.0.1 ', 11211);/* Add multiple servers */$array = Array ( Array (' 127.0.0.1 ', 11211), Array (' 127.0.0.1 ', 11211), $m->addservers ($array);/* View server Status */print_r ($m GetStats ());/* View server-side version number */print_r ($m->getversion ());/* Data class */$m->add (' Mkey ', ' Mvalue ', 0);//The third parameter is the time the data exists, 0 means permanent echo $m->get (' Mkey '),////To get the data/* Assuming that the same key value is added two times, the back of the operation will not overwrite the previous value, if you want to replace, use replace*/$m->replace (' Mkey ', ' mvalue2 ');/* You can also add data using the Set method table, which has the advantage of creating new data when our data doesn't exist, overwriting the original value if it exists */$m->add (' Mkey ', ' Mvalue ', 600);/* Delete data */$m->delete (' Mkey ');/* Clears all caches in the memcache */$m->flush ();/* operates +1 or + arbitrary values for the plastic data in Memcache */$m->set (' num ' , 5, 0); $m->increment (' num ', 5);//each time the page is refreshed, num 5$m->get (' num ');/* Decrement usage same *//* the method below only supports memcached, Do not support memcache*//* add multiple Data *///original method, multiple use Set ()//now can use Setmulti () $data = Array (' key ' = ' value ', ' key1 ' = ' value1 ') ; $m->setmulti ($data, 0); $result = $m->getmulti (Array (' key ', ' Key1 '));//Get Multiple Data print_r ($result);//Delete multiple stripsData $m->deletemulti (Array (' key ', ' Key1 '));//Returns the encoding (in the form of a number) returned from the last operation to see the meaning of each encoding in the manual echo $m->getresultcode (); such as successful return 0//get operation result Echo $m->getresultmessage ();//For example, successful return success

encapsulates one of its own memcache classes

memcached.class.php<?php/* Package own Memcached Class 1, extensibility 2, adjustable 3, as simple as possible operation, a method of various functions *//* through an S () method to implement set (), get (), delete () Operation set S ($key, $value, $time) get S ($key) Delete s ($key, NULL) */class mem{Private $type = ' Memcached ';//For extensibility, the instantiation may be    Memcache may also be memcached private $m;    Private $time = 0;    Private $error;    Private $debug = ' true '; Public Function __construct () {if (!class_exists ($this->type)) {$this->error= "No". $this->t            Ype        return false;        }else{$this->m=new $this->type;    }}//Add server public Function Addserver ($arr) {$this->m->addservers ($arr); The Public function s ($key, $value = ", $time =null) {$number = Func_num_args ();//The function is used to determine if a few parameters are passed over the IF ($nu        Mber = = 1) {return $this->get ($key); }else if ($number >= 2) {if ($value = = = NULL) {//must use "all equals", because if not all equals, pass over 0 will also pass $this->delete            ($key); }else{$This->set ($key, $value, $time); }}} Private function set ($key, $value, $time =null) {if ($time = = = NULL) $time = $this-        >time ();        $this->m->set ($key, $value, $time);            if ($this->debug) {if ($this->m->getresultcode ()! = 0) {return false;        }}} Private function Get ($key) {$result = $this->m->get ($key);            if ($this->debug) {if ($this->m->getresultcode ()! = 0) {return false;    }} return $result;    } Private Function Delete ($key) {$this->m->delete ($key);        Public Function GetError () {if ($this->error) {return $this->error ();        }else{return $this->m->getresultmessage (); }    }}

project using Memcache
1, Instant cache
Comparison works like a news detail page, when the first person enters the page, generates the cache, and when the person behind it enters the page, You can get the data directly from the cache, and you can set an expiration time for the data, so that the people who see the news will be able to clear the cache in time, so that the memory can be saved for the purpose of
2, generate cache in advance
This method of generating the cache is more suitable for the large amount of traffic and more data, similar to the home page of this situation. You can use a timed script to generate the cache in advance of
3, a permanent cache
This caching scheme is more appropriate for a separate page, it is very slow to modify, you can generate a permanent cache

**memcache Introduction: **memcache is a set of distributed cache system, distributed means can be installed on multiple servers at the same time Memcache services, which can achieve a good cluster effect. High speed, because the memcache data is maintained in memory, it reads faster than the data stored on the hard disk.
role: When our application access is relatively large, the database pressure is also very large, memcache can add a buffer layer between the application and the database, which is the data we have read from the database, the second or next time we read it, You can directly access the Memcache to read this data, thus reducing the pressure of MySQL and so on database
How to Memcache: In fact, it can be understood, it is a database with only one table, this table has two fields, respectively, key and Value,value are saved data, key is the ID of this data, to ensure the uniqueness of the search
Usage Scenarios:
(1) Non-persistent storage: The data storage requirements are not high, that is, if the data is lost, it will not be too much impact on the system, because when the system is powered off or restarted after the memory will be emptied, then the data saved in the memcache will be erased. So use memcache as a cache instead of a real database.
(2) Distributed storage: not suitable for single use, because Memcache memory consumption is very large, if using memcache, it is recommended to install it on a separate machine as a cache system, rather than the memcache and the database are loaded into a machine.
(3) Key/value storage: Simple format, does not support list, array data format

Memcached and Memcache are two versions, recommended memcached, it has more improvements and functional functions, is memcache upgrade version, speed and stability are higher

Installing memcached
1,memcache installation of the service side
(1) Compile and install, Libevent Memcache
Install libevent This extension, the advantage of compiling and installing is that you can make some custom settings during the installation, such as specifying where the software is installed, such as what errors have occurred during the compilation and installation process, and if you do not know much about Linux, you may be more difficult to handle errors
(2) Install using the Dependency management tool yum, Apt-get

Actual installation: (the operating system is 64-bit CentOS)
If you want to compile the installation, you need to download the installation package in advance libevent, memcached
This is installed using the dependency management tool

#yum Install memcached

Start memcached

#/usr/bin/memcached-d-L 127.0.0.1-p 11211-m 150-u root/*    -D: Daemon mode starts. The daemon is that when you launch from the terminal window, the program still    does the-l: Specify the IP address    -P: Specify the port number-    m: How much memory is allocated for memcached, here is the M-    u: in which identity to start memcached (It is best not to use the Super Admin user on the line) */

You can use PS to see if the memcached process is started

#ps-ef | grep memcached

installation of the 2,memcache client
1, install the pre-extension libmemcached
Download good libmemcached and memcached, unzip the libmemcached
Here to use the compiled installation, into the extracted folder
Perform

#./configure--prefix=/usr/lib/libmemcached then executes #make && Makeinstall

2, install memcached Extension for PHP
Unzip the memcached and go to the unzip directory
Installing the memcached extension using the Phpize method

#phpize此时就会做出一个configure的文件 #./configure--with-php-config=/usr/local/php/bin/php-config--with-libmemcached-dir= /USR/LIB/LIBMEMCACHED-SASL behind is the specified PHP configuration file and the location of the newly installed libmemcached, everyone according to their own configuration file path to fill #make#make install after you execute make install , we will see an extension directory, add the path to the PHP configuration file php.ini and then restart the server environment to see the PHP extension #php-m | grep memecached

Using memcached in PHP
System classes:addserver, Addservers, GetStats, getversion
Data classes: Add,set,delete, flush, replace, increment,get
Advanced classes: Setmulti, Deletemulti, Getmulti, Getresultcode, Getresultmessage
More about memecached, can be viewed on the PHP website (php.net)

test.php<?php/* System class */$m = new Memcached ();/* Add server */$m->addserver (' 127.0.0.1 ', 11211);/* Add multiple servers */$array = Array ( Array (' 127.0.0.1 ', 11211), Array (' 127.0.0.1 ', 11211), $m->addservers ($array);/* View server Status */print_r ($m GetStats ());/* View server-side version number */print_r ($m->getversion ());/* Data class */$m->add (' Mkey ', ' Mvalue ', 0);//The third parameter is the time the data exists, 0 means permanent echo $m->get (' Mkey '),////To get the data/* Assuming that the same key value is added two times, the back of the operation will not overwrite the previous value, if you want to replace, use replace*/$m->replace (' Mkey ', ' mvalue2 ');/* You can also add data using the Set method table, which has the advantage of creating new data when our data doesn't exist, overwriting the original value if it exists */$m->add (' Mkey ', ' Mvalue ', 600);/* Delete data */$m->delete (' Mkey ');/* Clears all caches in the memcache */$m->flush ();/* operates +1 or + arbitrary values for the plastic data in Memcache */$m->set (' num ' , 5, 0); $m->increment (' num ', 5);//each time the page is refreshed, num 5$m->get (' num ');/* Decrement usage same *//* the method below only supports memcached, Do not support memcache*//* add multiple Data *///original method, multiple use Set ()//now can use Setmulti () $data = Array (' key ' = ' value ', ' key1 ' = ' value1 ') ; $m->setmulti ($data, 0); $result = $m->getmulti (Array (' key ', ' Key1 '));//Get Multiple Data print_r ($result);//Delete multiple stripsData $m->deletemulti (Array (' key ', ' Key1 '));//Returns the encoding (in the form of a number) returned from the last operation to see the meaning of each encoding in the manual echo $m->getresultcode (); such as successful return 0//get operation result Echo $m->getresultmessage ();//For example, successful return success

encapsulates one of its own memcache classes

memcached.class.php<?php/* Package own Memcached Class 1, extensibility 2, adjustable 3, as simple as possible operation, a method of various functions *//* through an S () method to implement set (), get (), delete () Operation set S ($key, $value, $time) get S ($key) Delete s ($key, NULL) */class mem{Private $type = ' Memcached ';//For extensibility, the instantiation may be    Memcache may also be memcached private $m;    Private $time = 0;    Private $error;    Private $debug = ' true '; Public Function __construct () {if (!class_exists ($this->type)) {$this->error= "No". $this->t            Ype        return false;        }else{$this->m=new $this->type;    }}//Add server public Function Addserver ($arr) {$this->m->addservers ($arr); The Public function s ($key, $value = ", $time =null) {$number = Func_num_args ();//The function is used to determine if a few parameters are passed over the IF ($nu        Mber = = 1) {return $this->get ($key); }else if ($number >= 2) {if ($value = = = NULL) {//must use "all equals", because if not all equals, pass over 0 will also pass $this->delete            ($key); }else{$This->set ($key, $value, $time); }}} Private function set ($key, $value, $time =null) {if ($time = = = NULL) $time = $this-        >time ();        $this->m->set ($key, $value, $time);            if ($this->debug) {if ($this->m->getresultcode ()! = 0) {return false;        }}} Private function Get ($key) {$result = $this->m->get ($key);            if ($this->debug) {if ($this->m->getresultcode ()! = 0) {return false;    }} return $result;    } Private Function Delete ($key) {$this->m->delete ($key);        Public Function GetError () {if ($this->error) {return $this->error ();        }else{return $this->m->getresultmessage (); }    }}

project using Memcache
1, Instant cache
Comparison works like a news detail page, when the first person enters the page, generates the cache, and when the person behind it enters the page, You can get the data directly from the cache, and you can set an expiration time for the data, so that the people who see the news will be able to clear the cache in time, so that the memory can be saved for the purpose of
2, generate cache in advance
This method of generating the cache is more suitable for the large amount of traffic and more data, similar to the home page of this situation. You can use a timed script to generate the cache in advance of
3, a permanent cache
This caching scheme is more appropriate for a separate page, it is very slow to modify, you can generate a permanent cache

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.