1. 程式人生 > >PHP 使用 Rabbitmq Demo

PHP 使用 Rabbitmq Demo

訂閱者 change password server rect ++ direct 類型 127.0.0.1

一、發布消息類(client.php),發布者

<?php
$conn = [
    ‘host‘ => ‘127.0.0.1‘,
    ‘port‘ => ‘5672‘,
    ‘login‘ => ‘guest‘,
    ‘password‘ => ‘guest‘,
    ‘vhost‘=>‘/‘
];

//創建連接和channel
$conn = new AMQPConnection($conn);
if(!$conn->connect()) {
    die("Cannot connect to the broker!\n");
}
$channel = new AMQPChannel($conn);

// 用來綁定交換機和隊列
$routingKey = ‘key_1‘;

$ex = new AMQPExchange($channel);
//  交換機名稱
$exchangeName = ‘ex1‘;
$ex->setName($exchangeName);

// 設置交換機類型
$ex->setType(AMQP_EX_TYPE_DIRECT);
// 設置交換機是否持久化消息
$ex->setFlags(AMQP_DURABLE);
$ex->declare();

for($i=0; $i<5; ++$i){
    echo "Send Message:".$ex->publish(date(‘H:i:s‘)."用戶".$i."註冊" , $routingKey )."\n";
}

 

二、接受消息類(server.php),訂閱者

<?php
$conn = [
    ‘host‘ => ‘127.0.0.1‘,
    ‘port‘ => ‘5672‘,
    ‘login‘ => ‘guest‘,
    ‘password‘ => ‘guest‘,
    ‘vhost‘=>‘/‘
];

//創建連接和channel
$conn = new AMQPConnection($conn);
if(!$conn->connect()) {
    die("Cannot connect to the broker!\n");
}
$channel = new AMQPChannel($conn);
$exchangeName = ‘ex1‘;

//創建交換機
$ex = new AMQPExchange($channel);
$ex->setName($exchangeName);

$ex->setType(AMQP_EX_TYPE_DIRECT); //direct類型
$ex->setFlags(AMQP_DURABLE); //持久化
$ex->declare();

//  創建隊列
$queueName = ‘queue1‘;
$q = new AMQPQueue($channel);
$q->setName($queueName);
$q->setFlags(AMQP_DURABLE);
$q->declareQueue();

// 用於綁定隊列和交換機,跟 send.php 中的一致。
$routingKey = ‘key_1‘;
$q->bind($exchangeName,  $routingKey);

//接收消息
$q->consume(function ($envelope, $queue) {
    $msg = $envelope->getBody();
    echo $msg."\n"; //處理消息
}, AMQP_AUTOACK);

$conn->disconnect();

  

三、需要將訂閱者常駐於後臺進程。

這裏先使用下命令

php server.php

 然後打開另一個終端,使用

php client.php

 

PHP 使用 Rabbitmq Demo