我是靠谱客的博主 过时雪碧,这篇文章主要介绍php 中使用Rabbitmq实现实现消息发送和接收,现在分享给大家,希望可以做个参考。

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

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

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

代码如下
send.php

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(44)

评论列表共有 0 条评论

立即
投稿
返回
顶部