PHP+RabbitMQ学习笔记

一、环境搭建

  1. 下载并安装erlang

  2. 下载并安装rabbitmq

二、初始化项目

  1. 创建一个rabbit目录,在此目录下创建composer.json文件,文件内容如下
1
2
3
4
5
{
"require":{
"php-amqplib/php-amqplib": ">=2.6.1"
}
}
  1. 然后通过composer install 命令加载所需要的库

三、代码

  1. 创建消息发布脚本 send.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$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!'\n";
$channel->close();
$connection->close();
  1. 创建消息消费脚本 recieve.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;

$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\n";

$callback = function ($msg) {
echo ' [x] Received ', $msg->body, "\n";
};
$channel->basic_consume('hello', '', false, true, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$connection->close();

四、运行(已经配置好php环境变量)

在rabbit目录开两个命令窗口,分别执行 php recieve.php 和 php send.php 命令

五、结果

  1. 执行 php recieve.php 后结果:
    recieve.php

  2. 执行 php send.php 后结果:
    send.php

recieve.php