概述
php 中使用Rabbitmq实现实现消息发送和接收
1,建立一个send.php文件用来发送消息
2,建立一个 receive.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
最后
以上就是过时雪碧为你收集整理的php 中使用Rabbitmq实现实现消息发送和接收的全部内容,希望文章能够帮你解决php 中使用Rabbitmq实现实现消息发送和接收所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复