Skip to main content

1、Hello World

http://previous.rabbitmq.com/v3_5_7/tutorials/tutorial-one-php.html

send.php(发送)

<?php
//包含库并使用必要的类
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
//创建到服务器的连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
//声明一个队列供我们发送; 然后我们可以向队列发布消息:
$channel->queue_declare('hello', false, false, false, false);

$msg = new AMQPMessage('Hello World!');
$channel->basic_publish($msg, '', 'hello');

echo " [x] Sent 'Hello World!'\n";

$channel->close();
$connection->close();
?>

receive.php(接收)

<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 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";
};
//我们的代码将阻止我们的$channel有回调。每当我们收到消息时,我们的$callback函数将传递收到的消息。
$channel->basic_consume('hello', '', false, true, false, false, $callback);

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

$channel->close();
$connection->close();
?>

延伸

send.php

//包含库并使用必要的类
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
//创建到服务器的连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
//声明一个队列供我们发送; 然后我们可以向队列发布消息:
$channel->queue_declare('hello', false, false, false, false);

$data[1]='222';
$data[2]='333';

$msg = new AMQPMessage(json_encode($data));
$channel->basic_publish($msg, '', 'hello');

echo " [x] Sent 'Hello World!'\n";

$channel->close();
$connection->close();

receive.php

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

$connection = new AMQPStreamConnection('localhost', 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";
print_r(json_decode($msg->body));
};
//我们的代码将阻止我们的$channel有回调。每当我们收到消息时,我们的$callback函数将传递收到的消息。
$channel->basic_consume('hello', '', false, true, false, false, $callback);

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

$channel->close();
$connection->close();