- 相關(guān)推薦
用PHP基于Redis消息隊列實現(xiàn)發(fā)布微博的方法
PHP基于Redis消息隊列實現(xiàn)發(fā)布微博的方法,結(jié)合實例形式分析了php+redis數(shù)據(jù)庫的安裝、連接、讀取、插入等相關(guān)操作技巧,需要的朋友可以參考下。
phpRedisAdmin :github地址 圖形化管理界面
git clone [url]https://github.com/ErikDubbelboer/phpRedisAdmin.git[/url]
cd phpRedisAdmin
git clone [url]https://github.com/nrk/predis.git[/url] vendor
首先安裝上述的Redis圖形化管理界面,能夠方便的管理Redis數(shù)據(jù)
為了降低Mysql的并發(fā)數(shù),先把用戶的微博存在Redis中
假設(shè)用戶發(fā)布的時候需要三個字段,uid(用戶ID號),username(用戶姓名),content('用戶的評論')
比如用戶傳遞以下信息 //此處需要安裝phpredis
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// 連接redis
$web_info= array(
'uid' => '123456',
'username' => '123',
'content' =>'123'
);
//將數(shù)組轉(zhuǎn)成json來存儲
$list = json_encode($web_info);
//lpush向KEY對應(yīng)的頭部添加一個字符串元素
$redis->lpush('weibo_lists',$list);
$redis->close();
///var_dump(json_encode($web_info));
var_dump($list);
?>
此處可以看到我們的redis已經(jīng)有數(shù)據(jù)了
//創(chuàng)建一個PDO數(shù)據(jù)庫鏈接 data.php
class qq{
public function post($uid='',$username='',$content=''){
try{
$dsn = "mysql:host;dbname=localhost;dbname=test";
$db = new PDO($dsn,'root','root');
$db->exec("SET NAMES UTF8");
$sql ="insert into test(uid,username,content)values('$uid','$username','$content')";
$db->exec($sql);
}catch(PDOException $e){
$e->getMessage();
}
}
}
//處理redis數(shù)據(jù)庫的數(shù)據(jù) 并把數(shù)據(jù)放到MYSQL數(shù)據(jù)庫中
include "data.php";
$qq = new qq();
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
//返回的列表的大小。如果列表不存在或為空,該命令返回0。如果該鍵不是列表,該命令返回FALSE
if($redis -> lsize('weibo_lists')){
//從LIST頭部刪除并返回刪除數(shù)據(jù)
$info = $redis->rPop('weibo_lists');
$info = json_decode($info);
$qq->post($info->uid,$info->username,$info->content);
}
$redis->close();
var_dump($info);
?>
【用PHP基于Redis消息隊列實現(xiàn)發(fā)布微博的方法】相關(guān)文章:
php實現(xiàn)Session存儲到Redis03-02
php中使用redis隊列操作實例代碼03-02
PHP實現(xiàn)多線程的方法03-29
php頁面緩存實現(xiàn)方法11-27
PHP實現(xiàn)獲取域名的方法小結(jié)06-08