memcache notes

WBOY
WBOYOriginal
2016-07-29 09:16:08911browse

The result set of the database query is usually saved in memcached (as for why cache is used here, you can search for the keyword "cache" on your own)
Get it directly from memcached the next time you visit,
No more database queries Operation,
This can reduce the burden on the database to a great extent.
************************
* Simple demo1 *
************************ *
$m = new Memcache();
$m->connect('172.16.0.3', 8888);//Duoduo test cache
$data = 'content'; //Data that needs to be cached
$m- >add('mykey', $data);
echo $m->get('mykey'); // Output content
$m->replace('mykey', 'data'); //Replace The content is dataecho $m->get('mykey');//Output data
$m->delete('mykey'); //Delete echo $m->get('mykey'); // Output false because it has been deleted..
************************
* Simple demo2 *
*********** *************
Note: Usually the value after the SQL statement md5() is used as the unique identifier key.
//Connect memcache
$m = new Memcache();
$m->connect('localhost', 11211); //The local default connection port number is 11211
//I will connect to the database Not written anymore.
$sql = 'SELECT * FROM users';
$key = md5($sql); //md5 SQL command is used as the unique identifier of memcache
$rows = $m->get($key) ; //Re-memcache to get the data first
if (!$rows) {
//If $rows is false, then there is no data, then write the data
$res = mysql_query($sql);
$rows = array ();
while ($row = mysql_fetch_array($res)) {
$rows[] = $row;
}
$m->add($key, $rows);
//Write heavy database here For data obtained in , so the database will be read once, and when the program is accessed again, it will be obtained directly from memcache.
?>


Copyright Statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.

The above introduces the memcache notes, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn