這篇文章主要介紹了PHP基於Redis訊息佇列實現發布微博的方法,結合執行個體形式分析了php+redis資料庫的安裝、串連、讀取、插入等相關操作技巧,需要的朋友可以參考下
phpRedisAdmin :github地址 圖形化管理介面
git clone [url]https://github.com/ErikDubbelboer/phpRedisAdmin.git[/url]cd phpRedisAdmingit clone [url]https://github.com/nrk/predis.git[/url] vendor
首先安裝上述的Redis圖形化管理介面,能夠方便的管理Redis資料
為了降低Mysql的並發數,先把使用者的微博存在Redis中
假設使用者發布的時候需要三個欄位,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');//將數組轉成json來儲存$list = json_encode($web_info);//lpush向KEY對應的頭部添加一個字串元素$redis->lpush('weibo_lists',$list);$redis->close();///var_dump(json_encode($web_info));var_dump($list);?>
此處可以看到我們的redis已經有資料了
//建立一個PDO資料庫連結 data.phpclass 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資料庫的資料 並把資料放到MYSQL資料庫中include "data.php";$qq = new qq();$redis = new Redis();$redis->connect('127.0.0.1', 6379);//返回的列表的大小。如果列表不存在或為空白,該命令返回0。如果該鍵不是列表,該命令返回FALSEif($redis -> lsize('weibo_lists')){ //從LIST頭部刪除並返回刪除資料 $info = $redis->rPop('weibo_lists'); $info = json_decode($info); $qq->post($info->uid,$info->username,$info->content);}$redis->close();var_dump($info);?>
我們能看到資料庫已經有資料了
以上就是本文的全部內容,希望對大家的學習有所協助。