三、PHP 中实现消息发送和接收
send.php
<?php
/**
* 发送消息
*/
$exchangeName = 'demo';
$routeKey = 'hello';
$message = 'Hello World!';
// 建立TCP连接
$connection = new AMQPConnection([
'host' => 'localhost',
'port' => '5672',
'vhost' => '/',
'login' => 'guest',
'password' => 'guest'
]);
$connection->connect() or die("Cannot connect to the broker!\n");
try {
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName($exchangeName);
$exchange->setType(AMQP_EX_TYPE_DIRECT);
$exchange->declareExchange();
echo 'Send Message: ' . $exchange->publish($message, $routeKey) . "\n";
echo "Message Is Sent: " . $message . "\n";
} catch (AMQPConnectionException $e) {
var_dump($e);
}
// 断开连接
$connection->disconnect();
receive.php
<?php
/**
* 接收消息
*/
$exchangeName = 'demo';
$queueName = 'hello';
$routeKey = 'hello';
// 建立TCP连接
$connection = new AMQPConnection([
'host' => 'localhost',
'port' => '5672',
'vhost' => '/',
'login' => 'guest',
'password' => 'guest'
]);
$connection->connect() or die("Cannot connect to the broker!\n");
$channel = new AMQPChannel($connection);
$exchange = new AMQPExchange($channel);
$exchange->setName($exchangeName);
$exchange->setType(AMQP_EX_TYPE_DIRECT);
echo 'Exchange Status: ' . $exchange->declareExchange() . "\n";
$queue = new AMQPQueue($channel);
$queue->setName($queueName);
echo 'Message Total: ' . $queue->declareQueue() . "\n";
echo 'Queue Bind: ' . $queue->bind($exchangeName, $routeKey) . "\n";
var_dump("Waiting for message...");
// 消费队列消息
while(TRUE) {
$queue->consume('processMessage');
}
// 断开连接
$connection->disconnect();
function processMessage($envelope, $queue) {
$msg = $envelope->getBody();
var_dump("Received: " . $msg);
$queue->ack($envelope->getDeliveryTag()); // 手动发送ACK应答
}
测试:
打开两个终端,先运行接收者脚本监听消息发送:
php receive.php
在另一个终端中运行消息发送脚本:
php send.php
然后会在消费者终端中看到消息被接收并打印出来。
4 Comments
打开两个终端是什么意思啊,能不能说的具体一点?
两个终端窗口(Terminal),即 Unix 里面的命令行窗口