RabbitMQ学习(三) --- 使用官网提供的php composer包连接
官网链接:
https://www.rabbitmq.com/tutorials/tutorial-one-php.html
https://xiaoxiami.gitbook.io/rabbitmq_into_chinese_php/ying-yong-jiao-cheng/php-ban/1-hello_world
对应的代码:
https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/php/receive.php
一、安装composer拓展
新建composer.json文件,添加代码
{ "require": { "php-amqplib/php-amqplib": "2.6.1" } }
安装拓展:
composer install
二、使用代码
消费者代码receive.php
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLibConnectionAMQPStreamConnection; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); echo " [*] Waiting for messages. To exit press CTRL+C "; $callback = function ($msg) { echo ' [x] Received ', $msg->body, " "; }; $channel->basic_consume('hello', '', false, true, false, false, $callback); while(count($channel->callbacks)) { $channel->wait(); } $channel->close(); $connection->close();
生产者代码send.php
<?php require_once __DIR__ . '/vendor/autoload.php'; use PhpAmqpLibConnectionAMQPStreamConnection; use PhpAmqpLibMessageAMQPMessage; $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest'); $channel = $connection->channel(); $channel->queue_declare('hello', false, false, false, false); $msg = new AMQPMessage('Hello World!'); $channel->basic_publish($msg, '', 'hello'); echo " [x] Sent 'Hello World!' "; $channel->close(); $connection->close();
三、使用
先启动消费者 receive.php 接收消息
再启动 生产者 send.php 发送消息
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/13406908.html
转载请著名出处!谢谢~~