标签:部分 one ice color heap imp json es2017 image
这里我们弱化broker内部构造。将整体分为三部分。
P:producer。生产者。
C:Consumer。消费者。
queue:队列。
后面的代码都依赖于 the php-amqplib API
1. 新建composer.json
{ "require": { "php-amqplib/php-amqplib": ">=2.6.1" } }
2. composer.phar install
talk is cheap , show you the code
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();
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(); }
执行
打开两个终端,分别执行两个脚本。
终端一:
终端二:
终端一收到终端二发送的消息。
标签:部分 one ice color heap imp json es2017 image
原文地址:http://www.cnblogs.com/hejun695/p/7687380.html