使用PHP连接、操纵Memcached的原理和教程

英文原文:

http://www.9lessons.info/2012/02/memcached-with-php.html

作者在这个网站 demos.9lessons.info 中使用了memcached。

假设我们的数据库如下:

Sample database demos table contains id, title and link.

CREATE TABLE demos
(
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(300), 
link VARCHAR(300), 
);
First User Request
First request goes to database server at the same time data object storing in Memcached server. 
Second User Request
Second user request data comes from Memcached object. 
Memcached Installation
Lots of better resources available on web please follow the links.php_memcache.dll 
INSTALLING MEMCACHED ON AMAZON LINUX AMI - QUICK AND EASY.
INSTALLING MEMCACHED ON Windows.
install Memcached on Xampp on Windows 7
Memcached for PHP 5.3 on Windows 7.

index.php
Contains PHP code. 
php操作memcached示例:
<?php
include('db.php');
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

//缓存服务器中,都是键值对,这里我们设定唯一的键
$key = md5('www.crazyant.net'); 
$cache_result = array();
//根据键,从缓存服务器中获取它的值
$cache_result = $memcache->get($key); 

//如果存在该键对应的值,说明缓存中存在该内容
if($cache_result){
    //那我们直接取出缓存的内容就可以了
    $demos_result=$cache_result;
} else {
    //如果缓存中没有该键对应的值数据,说明请求是第一次到达

    //首先,我们需要从数据库中取出该值
    $v=mysql_query("select * from demos order by id desc");
    while($row=mysql_fetch_array($v)){
        //取出的内容就是我们需要的
        $demos_result[]=$row; 
    }
    //最后,将这次从数据库取出的内容,放到Memcached缓存服务器,这里就是缓存的精髓
    $memcache->set($key, $demos_result, MEMCACHE_COMPRESSED, 1200); 
}

//前面的所有操作,最终返回了我们需要的数据
 foreach($demos_result as $row){
    echo '<a href='.$row['link'].'>'.$row['title'].'</a>';
}

?>

db.php

$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) 
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
 
原文地址:https://www.cnblogs.com/youxin/p/3406191.html