RabbitMq初探——Hello World
Posted 王大西
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RabbitMq初探——Hello World相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
rabbitMQ实战---------使用pika库实现hello world