RabbitMQ 安装

环境:Linux Centos7

安装 RabbitMQ 前, 需先安装 Erlang
1
2
3
4
#若无法使用 yum 安装 erlang, 去  下载对应的 rpm 
yum install erlang
#若无法使用 yum 安装 rabbitmq-server, 去 下载对应的 rpm[
yum install rabbitmq-server-3.7.2-1.el7.noarch.rpm
测试 erlang 是否安装成功
1
2
3
4
5
6
7
8
[root@localhost rabbitmq]# erl
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:1:1] [ds:1:1:10] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V9.2 (abort with ^G)
1> 9+3.
12
2> halt().
[root@localhost rabbitmq]#
RabiitMQ 常用命令
1
2
3
4
5
6
#启动 RabbitMQ Server
service rabbitmq-server start
#停止 RabiitMQ Server
service rabbitmq-server stop
#查看 RabiitMQ Server 状态
rabbitmqctl status
安装 php-amqplib 客户端,参考地址
1
2
3
4
5
6
7
8
#添加一个composer.json 到项目中
{
"require" : {
"php-amqplib/php-amqplib" : ">= 2.6.1"
}
}
#运行命令
composer install
demo 示例,在项目目录下新建 send.php 和 receive.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#send.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

try {
// 创建一个到 RabbitMQ 服务器的连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
// 声明一个 hello 队列[不存在时才会创建]
$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();
} catch (Exception $e) {
echo $e->getMessage();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#receive.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

try {
// 创建一个到 RabbitMQ 服务器的连接
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
// 声明一个 hello 队列
$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();
}
} catch (Exception $e) {
echo $e->getMessage();
}
运行
1
2
3
4
#在终端中,先运行 receive.php 
php receive.php
#再运行 send.php
php send.php
问题

查看 RabbitMQ Server 状态 时, 报 Error: unable to perform an operation on node ‘rabbit@localhost’. Please see diagnostics information and suggestions below. 错误

1
systemctl restart rabbitmq-server.service
0%