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 PhpAmqpLibConnectionAMQPStreamConnection; use PhpAmqpLibMessageAMQPMessage; $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' "; //close the channel and connection; $channel->close(); $connection->close();
receive.php
require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLibConnectionAMQPStreamConnection; $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', " "; $callback = function($msg) { echo "[x] Received ", $msg->body, " "; sleep(substr_count($msg->body, '.')); echo "[x] Done "; }; $channel->basic_consume('hello', '', false, true, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); }
执行
打开两个终端,分别执行两个脚本。
终端一:
终端二:
终端一收到终端二发送的消息。