php 中使用Rabbitmq实现实现消息发送和接收

php 中使用Rabbitmq实现实现消息发送和接收

1,建立一个send.php文件用来发送消息

2,建立一个 receive.php 文件用来接收消息

代码如下
send.php

 '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 

 '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

你可能感兴趣的:(php,rabbitmq)