《PHP應(yīng)用:PHP使用redis消息隊(duì)列發(fā)布微博的方法示例》要點(diǎn):
本文介紹了PHP應(yīng)用:PHP使用redis消息隊(duì)列發(fā)布微博的方法示例,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
PHP編程本文實(shí)例講述了PHP使用redis消息隊(duì)列發(fā)布微博的方法.分享給大家供大家參考,具體如下:
PHP編程在一些用戶(hù)發(fā)布內(nèi)容應(yīng)用中,可能出現(xiàn)1秒上萬(wàn)個(gè)用戶(hù)同時(shí)發(fā)布消息的情況,此時(shí)使用mysql可能會(huì)出現(xiàn)" too many connections"錯(cuò)誤,當(dāng)然把Mysql的max_connections參數(shù)設(shè)置為更大數(shù),不過(guò)這是一個(gè)治標(biāo)不治本的方法.而使用redis的消息隊(duì)列,把用戶(hù)發(fā)布的消息暫時(shí)存儲(chǔ)在消息隊(duì)列中,然后使用多個(gè)cron程序把消息隊(duì)列中的數(shù)據(jù)插入到Mysql.這樣就有效的降低了Mysql的高并發(fā).具體實(shí)現(xiàn)原理如下:
PHP編程現(xiàn)有微博發(fā)布接口:
PHP編程
$weibo = new Weibo();
$uid = $weibo->get_uid();
$content =$weibo->get_content;
$time = time();
$webi->post($uid,$content,$time);
PHP編程此方法直接把微博內(nèi)容寫(xiě)入Mysql.具體過(guò)程省略.
PHP編程把消息寫(xiě)入到redis:
PHP編程
$redis = new Redis(localhost,6379);
$redis->connect();
$webiInfo = array('uid'=>get_uid(),'content'=>get_content(),'time'=>time());
$redis->lpush('weibo_list',json_encode($weiboInfo));
$redis->close();
PHP編程從redis中取出數(shù)據(jù):
PHP編程
while(true){
if($redis->lsize('weibo_list') > 0){
$info = $redis->rpop('weibo_list');
$info = json_decode($info);
}else{
sleep(1);
}
}
$weibo->post($info->uid,$info->content,$info->time);
//插入數(shù)據(jù)的時(shí)候可以用一次性插入多條數(shù)據(jù)的方法,避免循環(huán)插入,不停的循環(huán)插入可能會(huì)導(dǎo)致死鎖問(wèn)題.
PHP編程提示:可以運(yùn)行多個(gè)cron程序同時(shí)把消息隊(duì)列的數(shù)據(jù)插入到Mysql中,當(dāng)一臺(tái)Redis服務(wù)器不能應(yīng)付大量并發(fā)時(shí),使用一致性Hash算法,把并發(fā)分發(fā)到不同的Redis服務(wù)器.
PHP編程更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php+redis數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
PHP編程希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助.
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.snjht.com/jiaocheng/579.html