PHP使用ActiveMQ案例分析(附代碼)

來源:互聯網
上載者:User
這次給大家帶來PHP使用ActiveMQ案例分析(附代碼),PHP使用ActiveMQ的注意事項有哪些,下面就是實戰案例,一起來看一下。

使用點對點(Point To Point)模型

點對點模型特點:

  • 只有一個消費者可以接收到訊息

  • 不能重複消費

生產者producer.php代碼:

<?phptry {  // 1.建立串連  $stomp = new Stomp('tcp://47.52.119.21:61613');  // 2.執行個體化類  $obj = new Stdclass();  // 3.擷取資料  for($i=0; $i<3; $i++){    $obj->username = 'test';    $obj->password = '123456';    $queneName   = "/queue/userReg";    // 4.發送一個註冊訊息到隊列    $stomp->send($queneName, json_encode($obj));  }} catch (StompException $e) {  die('Connection failed: ' . $e->getMessage());}

消費者1consumer1.php代碼:

<?php$stomp = new Stomp('tcp://localhost:61613');$stomp->subscribe('/queue/userReg');while (true) {  //判斷是否有讀取的資訊  if ($stomp->hasFrame()) {    $frame = $stomp->readFrame();    $data = json_decode($frame->body, true);    var_dump($data);    $stomp->ack($frame);  }}

消費者2consumer2.php代碼:

<?php$stomp = new Stomp('tcp://localhost:61613');$stomp->subscribe('/queue/userReg');while (true) {  //判斷是否有讀取的資訊  if ($stomp->hasFrame()) {    $frame = $stomp->readFrame();    $data = json_decode($frame->body, true);    var_dump($data);    $stomp->ack($frame);  }}

執行結果圖如下:

使用發布/訂閱(Publish Subscribe)模型

發布/訂閱模型特點:

多個消費者都可以收到訊息
能重複消費
生產者producer.php代碼:

<?phptry {  // 1.建立串連  $stomp = new Stomp('tcp://47.52.119.21:61613');  // 2.執行個體化類  $obj = new Stdclass();  // 3.擷取資料  for($i = 0; $i < 3; $i++){    $obj->username = 'test';    $obj->password = '123456';    $queneName   = "/topic/userReg";    // 4.發送一個註冊訊息到隊列    $stomp->send($queneName, json_encode($obj));  }} catch (StompException $e) {  die('Connection failed: ' . $e->getMessage());}

消費者1consumer1.php代碼:

<?php$stomp = new Stomp('tcp://localhost:61613');$stomp->subscribe('/topic/userReg');while (true) {  //判斷是否有讀取的資訊  if ($stomp->hasFrame()) {    $frame = $stomp->readFrame();    $data = json_decode($frame->body, true);    var_dump($data);    $stomp->ack($frame);  }}

消費者2consumer2.php代碼:

?php$stomp = new Stomp('tcp://localhost:61613');$stomp->subscribe('/topic/userReg');while (true) {  //判斷是否有讀取的資訊  if ($stomp->hasFrame()) {    $frame = $stomp->readFrame();    $data = json_decode($frame->body, true);    var_dump($data);    $stomp->ack($frame);  }}

執行結果圖如下:

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

php與js開啟本地exe應用程式傳遞參數步驟詳解

如何?php刪除固定路徑下檔案夾與檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.