PHP基於Redis訊息佇列發布微博的方法詳解

來源:互聯網
上載者:User
這篇文章主要介紹了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);?>

我們能看到資料庫已經有資料了

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.