本文實例講述了PHP基于Redis消息隊列實現(xiàn)發(fā)布微博的方法。分享給大家供大家參考,具體如下:
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); ?>
我們能看到數(shù)據(jù)庫已經(jīng)有數(shù)據(jù)了
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+redis數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《PHP擴展開發(fā)教程》、《php+mysql數(shù)據(jù)庫操作入門教程》、《php+mysqli數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
【網(wǎng)站聲明】本站除付費源碼經(jīng)過測試外,其他素材未做測試,不保證完整性,網(wǎng)站上部分源碼僅限學習交流,請勿用于商業(yè)用途。如損害你的權(quán)益請聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。