安装 RabbitMQ 和 PHP 的步骤就不在这里说了。测试步骤如下:
mq
mq
目录mqc.php
消费者和 mqp.php
生产者两个文件php -f index.php mqp
生产消息php -f index.php mqc
消费消息├─PhpAmqpLib
│ ├─Channel
│ ├─Connection
│ ├─Exception
│ ├─Exchange
│ ├─Helper
│ │ └─Protocol
│ ├─Message
│ └─Wire
│ └─IO
├─test
│ ├─mqc.php
│ └─mqp.php
└─index.php
// 根据 namespace 自动加载
function my_autoloader($cName) {
include(__DIR__."/".$cName.".php");
}
spl_autoload_register("my_autoloader");
// 调生产者
function mqp() {
$p = new \test\mqp();
$p->p();
}
// 调消费者
function mqc() {
$c = new \test\mqc();
$c->c();
}
// 取命令行参数,执行对应函数
if (function_exists($argv[1])) {
$argv[1]();
}
namespace test;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class mqc {
public function c() {
$host = 'localhost';
$port = 5672;
$user = 'guest';
$password = 'guest';
$connection = new AMQPStreamConnection($host, $port, $user, $password, '/', false, 'AMQPLAIN', null, 'en_US', 3.0, 120.0, null, true, 60);
$channel = $connection->channel();
$channel->exchange_declare('myExchange', 'direct', false, true, false);
$channel->queue_declare('myQueue', false, true, false, false);
//闭包回调函数
$callback = function ($msg) {
echo $msg->body;
echo PHP_EOL;
};
$channel->basic_consume('myQueue', '', false, false, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();
}
}
namespace test;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class mqp {
public function p() {
echo 22;
$host = 'localhost';
$port = 5672;
$user = 'guest';
$password = 'guest';
$connection = new AMQPStreamConnection($host, $port, $user, $password, '/', false, 'AMQPLAIN', null, 'en_US', 3.0, 120.0, null, true, 60);
$channel = $connection->channel();
$channel->exchange_declare('myExchange', 'direct', false, true, false);
$channel->queue_declare('myQueue', false, true, false, false);
$channel->queue_bind('myQueue', 'myExchange', 'my');
//准备消息
$msg = new AMQPMessage('hello,我要发送的消息内容~~~'.time());
$channel->basic_publish($msg, 'myExchange', 'my');
$channel->close();
$connection->close();
}
}