1. Memcache安裝
11.png
12.png
13.png
檢驗memcached是否下載完,可以在[控制面板]->[管理工具]->[服務]中查看到memcached服務
終端輸入 Stats,顯示如下:
![15.png](http://upload-images.jianshu.io/upload_images/2648722-e5ed41c06a0f2d44.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
輸入:quit退出
memcache 管理:
16.png
17.png
linux常用組合來修改相關配置(在windows下可能不能用):
18.png
基本的memcached客戶端命令
19.png
20.png
簡單把設置的值遍歷出來
21.png
memcache php擴展模塊安裝
22.png
23.png
windows點擊下載
將擴展文件放到對應版本php的模塊文件(ext)中
打開php.ini配置文件,將extension=memcache.dll前的分號去掉闷愤,重啟apache就可以了
memcache在php中的使用
<?php
//創(chuàng)建memcache對象
$mem=new Memcache;
//連接memcache服務器
$mem->connect('localhost',11211);
//操作
//add添加
class test{
public $a=1;
public $b=2;
public $c=3;
}
$mem->add('one','this is memcache test!',
MEMCACHE_COMPRESSED,time()+60*60*24*31);
$mem->add('two',array("111","222","333"),MEMCACHE_COMPRESSED,time()+60*60*24*31);
$mem->add('three',new test(),MEMCACHE_COMPRESSED,time()+60*60*24*31);
//修改操作
//把上面add換成set默责,沒有鍵值則是添加
$mem->set('one','this is set!',
MEMCACHE_COMPRESSED,time()+60*60*24*31);
//取值get
$mem->get('one');
var_dump($mem->get('three'));
//刪除delete
$mem->delete('one');
//清除所有
$mem->flush();
//關閉memcache連接
$mem->close();
利用memcache進行數(shù)據(jù)庫數(shù)據(jù)緩存
<?php
//創(chuàng)建memcache對象
$mem= new Memcache;
//連接memcache服務器
$mem->connect('localhost',11211);
//數(shù)據(jù)庫的連接和操作
/*
*判斷如果內(nèi)存中有數(shù)據(jù)直接取出,沒有的話從數(shù)據(jù)庫中查詢;
*/
$sql="select id,name,age from test order by id";
//設置鍵為md5($sql),這樣服務器每次使用同樣的sql語句就會走內(nèi)存
$key=MD5($sql);
//直接從內(nèi)存memcache要數(shù)據(jù)
$data=$mem->get($key);
//判斷
if(empty($data)){
try{
$pdo= new PDO('mysql:host=localhost;dbname=test','root','910420');
}catch(PDOException $e){
echo "數(shù)據(jù)庫連接失旓躅酢:".$e->getMessage();
}
//獲取數(shù)據(jù)二跋,執(zhí)行語句
$stmt=$pdo->prepare($sql);
$stmt->execute();
//獲取所有數(shù)據(jù)
$data=$stmt->fetchAll(PDO::FETCH_ASSOC);
//把數(shù)據(jù)插入到memcache內(nèi)存中
$mem->set($key,$data,MEMCACHE_COMPRESSED,5);
var_dump($data);
}
//關閉數(shù)據(jù)庫
$mem->close();
設置分布式的memcache存取
分布式的存取只需要把上述代碼的連接connect換成多臺服務器就可以了战惊,連接代碼如下:
$mem->addServer('192.168.1.137',11211);
24.png