码迷,mamicode.com
首页 > 其他好文 > 详细

RabbitMq初探——Hello World

时间:2017-10-18 16:44:52      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:部分   one   ice   color   heap   imp   json   es2017   image   

HelloWorld

前言


 

这里我们弱化broker内部构造。将整体分为三部分。

技术分享

P:producer。生产者。

C:Consumer。消费者。

queue:队列。

后面的代码都依赖于 the php-amqplib API

 

composer安装php-amqplib 


 

1. 新建composer.json

{
    "require": {
        "php-amqplib/php-amqplib": ">=2.6.1"
    }
}

 2. composer.phar install 

 

Hello World


talk is cheap , show you the code

sender.php

require_once __DIR__ . ‘/vendor/autoload.php‘;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection(‘127.0.0.1‘, 5672, ‘guest‘, ‘guest‘);
$channel = $connection->channel();


$channel->queue_declare(‘hello‘, false, false, false, false);

$data = implode(" ", array_slice($argv, 1));
empty($data) && $data = "Hello World!";

$msg = new AMQPMessage($data);

$channel->basic_publish($msg, ‘‘, ‘hello‘);

echo " [x] Sent ‘$data‘\n";

//close the channel and connection;
$channel->close();
$connection->close();

 

receive.php

require_once __DIR__ . ‘/vendor/autoload.php‘;
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection(‘127.0.0.1‘, 5672, ‘guest‘, ‘guest‘);
$channel = $connection->channel();

$channel->queue_declare(‘hello‘, false, false, false, false);
echo ‘ [*] Waiting for messages. To exit press CTRL+C‘, "\n";

$callback = function($msg) {
    echo "[x] Received ", $msg->body, "\n";
    sleep(substr_count($msg->body, ‘.‘));
    echo "[x] Done\n";
};
$channel->basic_consume(‘hello‘, ‘‘, false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}

 

执行

打开两个终端,分别执行两个脚本。

终端一:

技术分享

 

终端二:

技术分享

 

终端一收到终端二发送的消息。

技术分享

 

RabbitMq初探——Hello World

标签:部分   one   ice   color   heap   imp   json   es2017   image   

原文地址:http://www.cnblogs.com/hejun695/p/7687380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!