赞
踩
1.发布消息
- <?php
- namespace Mobile\Controller;
- use Think\Controller;
- class TestController extends Controller {
- /**
- * 同一局域网下 RabbitMQ发布消息
- */
- public function rabbit_1(){
- //配置信息
- $conn_args = [
- 'host' => '192.168.0.103',//局域网下的另一台主机地址
- 'port' => '5672',//端口号
- 'login' => 'admin',//新建用户admin,(默认的guest用户只能用作本地登录)
- 'password' => 'admin',//密码
- 'vhost'=>'admin',//admin绑定的虚拟主机
- ];
- //创建连接
- $conn = new \AMQPConnection($conn_args);
- if (!$conn->connect()) {
- echo "content error";
- }
-
- //AMQ通道
- $channel = new \AMQPChannel($conn);
-
- //创建交换机对象
- $ex = new \AMQPExchange($channel);
- $e_name = 'admin'; //交换机名 - 名字随意
- $ex->setName($e_name);
-
- //发送消息
- $key = rand(1,1000);
- $k_route = 'answer_list'; //路由key - 名字随意
- $ex->publish('test_list_'.$key, $k_route);
-
- //断开连接
- $conn->disconnect();
- echo $key;
- }
-
- }
2.接收消息
- <?php
- //配置信息
- $conn_args = [
- 'host' => '192.168.0.103',//局域网下的另一台主机地址
- 'port' => '5672',//端口号
- 'login' => 'admin',//新建用户admin,默认的guest不能使用
- 'password' => 'admin',//密码
- 'vhost'=>'admin',//admin绑定的虚拟主机
- ];
-
- //创建连接和channel
- $conn = new AMQPConnection($conn_args);
- if (!$conn->connect()) {
- die("content error".PHP_EOL);
- }
-
- //AMQ通道
- $channel = new AMQPChannel($conn);
-
- //创建交换机
- $ex = new AMQPExchange($channel);
- $e_name = 'admin'; //交换机名 取用发布消息时,创建交换机对象时设置的名字
- $ex->setName($e_name);
- $ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型
- $ex->setFlags(AMQP_DURABLE); //持久化
- echo "Exchange Status:".$ex->declare().PHP_EOL;
-
- //创建队列
- $q = new AMQPQueue($channel);
- $q->setFlags(AMQP_DURABLE); //持久化
- echo "Message Total:".$q->declare().PHP_EOL;
-
- //绑定交换机与队列,并指定路由键
- $k_route = 'answer_list';//路由key
- echo 'Queue Bind: '.$q->bind($e_name, $k_route).PHP_EOL;
-
- //阻塞模式接收消息
- echo "Message:\n";
- while(true){
- $q->consume('processMessage');
- $q->consume('processMessage', AMQP_AUTOACK); //自动ACK应答
- }
- $conn->disconnect();
-
- /**
- * 消费回调函数
- * 处理消息
- */
- function processMessage($envelope, $queue) {
- $msg = $envelope->getBody();
- echo $msg.PHP_EOL; //处理消息
- $queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答
- }
- ?>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。