RabbitMQ學習之(四)_PHP操作RabbitMQ簡單Demo

OldBoy~發表於2018-01-09

原理流程

生產者主要做的是:建立連線-->建立channel-->建立交換機物件-->傳送訊息

消費者主要做的是:建立連線-->建立channel-->建立交換機-->建立佇列-->繫結交換機/佇列/路由鍵-->接收訊息

案例一:

生產者 

<?php  
$conn_args = array(
    'host' => '127.0.0.1',
    'port' => '5672',
    'login' => 'admin',
    'password' => 'admin',
    'vhost'=>'/'
);

$content = isset($_GET['content']) ? htmlspecialchars($_GET['content']) : '請輸入訊息';
//建立連線和channel  
$conn = new AMQPConnection($conn_args);  
if (!$conn->connect()) {  
    die("Cannot connect to the broker!\n");  
}  
$channel = new AMQPChannel($conn);  
  
//建立交換機  
$e_name = 'e_linvo'; //交換機名  
$ex = new AMQPExchange($channel);  
$ex->setName($e_name);  
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct型別  
$ex->setFlags(AMQP_DURABLE); //持久化  
$ex->declare();  
  
//echo "Send Message:".$ex->publish("TEST MESSAGE,key_1 by xust" . date('H:i:s', time()), 'key_1')."\n";  
//echo "Send Message:".$ex->publish("TEST MESSAGE,key_2 by xust" . date('H:i:s', time()), 'key_2')."\n";  
$ex->publish($content, 'key_1');  
echo "finish\n";  

消費者

<?php  
$conn_args = array(  
    'host' => '127.0.0.1',  
    'port' => '5672',  
    'login' => 'admin',  
    'password' => 'admin',  
    'vhost'=>'/'  
);  
  
$e_name = 'e_linvo'; //交換機名  
$q_name = 'q_linvo'; //佇列名  
$k_route = 'key_2'; //路由key  
  
//建立連線和channel  
$conn = new AMQPConnection($conn_args);  
if (!$conn->connect()) {  
    die("Cannot connect to the broker!\n");  
}  
$channel = new AMQPChannel($conn);  
  
//建立交換機  
$ex = new AMQPExchange($channel);  
$ex->setName($e_name);  
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct型別  
$ex->setFlags(AMQP_DURABLE); //持久化  
$ex->declare();  
  
//建立佇列  
$q = new AMQPQueue($channel);  
$q->setName($q_name);  
$q->setFlags(AMQP_DURABLE); //持久化  
$q->declare();     //最好佇列object在這裡declare()下,否則如果是新的queue會報錯  
  
//繫結交換機與佇列,並指定路由鍵,可以多個路由鍵  
$q->bind($e_name, 'key_1');  
//$q->bind($e_name, 'key_33');  
  
//阻塞模式接收訊息  
echo "Message:\n";  
$q->consume('processMessage', AMQP_AUTOACK); //自動ACK應答  
  
$conn->disconnect();  
  
/** 
 * 消費回撥函式 
 * 處理訊息 
 */  
function processMessage($envelope, $queue) {  
    var_dump($envelope->getRoutingKey());  
    $msg = $envelope->getBody();  
    mysql_insert($msg);  
  
}  
//訊息入庫 
function mysql_insert($json){  
   $pdo = new PDO("mysql:host=localhost;dbname=rabbitmq","root","000000",array(PDO::ATTR_PERSISTENT => true) );  
   $sql = "insert into rabbitmq_table(sJson) values ('{$json}')";  
   echo $sql."\n";  
    if ($pdo->exec($sql)){  
        echo "insert success\n";  
    } else {  
        echo "error\n";  
    }  
}  
//表結構
DROP TABLE IF EXISTS `rabbitmq_table`;
CREATE TABLE `rabbitmq_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sJson` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

啟動消費者程式,同時不斷請求生產者程式,檢視資料變化

 案例二:

生產者

<?php  
$routingkey='key2';
//設定你的連線
$conn_args = array('host' => 'localhost', 'port' => '5672', 'login' => 'admin', 'password' => 'admin');
$conn = new AMQPConnection($conn_args);
if ($conn->connect()) {
    echo "連結成功\n";
}else {
    echo "連結失敗 \n ";
}
//你的訊息
$message = json_encode(array('訊息測試','My RabbitMQ-PHP','訊息佇列'));
//建立channel
$channel = new AMQPChannel($conn);
//建立exchange
$ex = new AMQPExchange($channel);
$ex->setName('exchange');//建立名字
$ex->setType(AMQP_EX_TYPE_DIRECT);
$ex->setFlags(AMQP_DURABLE);
//$ex->setFlags(AMQP_AUTODELETE);
//echo "exchange status:".$ex->declare();
echo "exchange status:".$ex->declareExchange();
echo "\n";
for($i=0;$i<10;$i++){
        if($routingkey=='key2'){
                $routingkey='key';
        }else{
                $routingkey='key2';
        }
        $ex->publish($message,$routingkey);
}

消費者

<?php
$bindingkey='key2';
//連線RabbitMQ
$conn_args = array( 'host'=>'127.0.0.1' , 'port'=> '5672', 'login'=>'admin' , 'password'=> 'admin','vhost' =>'/');
$conn = new AMQPConnection($conn_args);
$conn->connect();
//設定queue名稱,使用exchange,繫結routingkey
$channel = new AMQPChannel($conn);
$q = new AMQPQueue($channel);
$q->setName('queue2');
$q->setFlags(AMQP_DURABLE);
$q->declare();
$q->bind('exchange',$bindingkey);
//訊息獲取
$messages = $q->get(AMQP_AUTOACK) ;
if ($messages){
var_dump(json_decode($messages->getBody(), true ));
}
$conn->disconnect();

案例三:

生產者

<?php
$conn_args = array(
    'host' => '127.0.0.1',
    'port' => '5672',
    'login' => 'admin',
    'password' => 'admin',
    'vhost'=>'/'
);
$e_name = 'e_linvo'; //交換機名
//$q_name = 'q_linvo'; //無需佇列名
$k_route = 'key_1'; //路由key

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

//訊息內容
$message = "我的RabbitMQ走通了~~";

//建立交換機物件
$ex = new AMQPExchange($channel);
$ex->setName($e_name);

//傳送訊息
//$channel->startTransaction(); //開始事務
for($i=0; $i<5; ++$i){
    echo "Send Message:".$ex->publish($message, $k_route)."\n";
}
//$channel->commitTransaction(); //提交事務

$conn->disconnect();

消費者

<?php  
//配置資訊
$conn_args = array(
    'host' => '127.0.0.1',
    'port' => '5672',
    'login' => 'admin',
    'password' => 'admin',
    'vhost'=>'/'
);
$e_name = 'e_linvo'; //交換機名
$q_name = 'q_linvo'; //佇列名
$k_route = 'key_1'; //路由key

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

//建立交換機
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct型別
$ex->setFlags(AMQP_DURABLE); //持久化
echo "Exchange Status:".$ex->declare()."\n";

//建立佇列
$q = new AMQPQueue($channel);
$q->setName($q_name);
$q->setFlags(AMQP_DURABLE); //持久化
echo "Message Total:".$q->declare()."\n";

//繫結交換機與佇列,並指定路由鍵
echo 'Queue Bind: '.$q->bind($e_name, $k_route)."\n";

//阻塞模式接收訊息
echo "Message:\n";
while(True){
    $q->consume('processMessage');
    //$q->consume('processMessage', AMQP_AUTOACK); //自動ACK應答
}
$conn->disconnect();

/**
* 消費回撥函式
* 處理訊息
*/
function processMessage($envelope, $queue) {
    $msg = $envelope->getBody();
    echo $msg."\n"; //處理訊息
    $queue->ack($envelope->getDeliveryTag()); //手動傳送ACK應答
}

然後分別命令列執行兩個程式,消費者程式處於監聽狀態,多次執行生產者測試,觀察效果

php /data/wwwroot/default/publisher.php  //執行生產者
php /data/wwwroot/default/consumer.php  //執行消費者

附加刪除佇列:

 

 

 

 

相關文章