Php Rabbitmq 环境搭建(附一个例子)

首先安装 erl 环境,其次安装 rabbitmq-server ,最后安装 amqp 扩展,安装完成之后使用 rabbitmqctl status 查看状态 。文末附上一个 生产消费消息 的 例子。

用到的命令如下:

#安装erlang环境
$ apt-get install erlang



#安装 rabbitmq-server
$ wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.5.7/rabbitmq-server-3.5.7.tar.gz
$ tar zxvf rabbitmq-server-3.5.7.tar.gz
$ cd rabbitmq-server-3.5.7/
$ make

$ apt-get update
$ apt-get install xmlto --fix-missing
$ make install 


#安装 rabbitmq-c 
wget https://github.com/alanxz/rabbitmq-c/releases/download/v0.5.0/rabbitmq-c-0.5.0.tar.gz  --no-check-certificate
$ tar -xzvf rabbitmq-c-0.5.0.tar.gz
$ cd rabbitmq-c-0.5.0/
$ ls
$ autoconf -i
$ ./configure --prefix=/usr/local/rabbitmq-c
$ make
$ make install

#安装php-amqp扩展
$ apt-cache search php-rmqp

$ apt-get install php-rmqp

生产消费消息的小例子

在项目中使用composer引入 amqp

$ composer require    php-amqplib/php-amqplib   2.6.1 

生产者 producer (send.php)

<?php

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();

消费者 consumer (receive.php)

<?php

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();
}

1 发送两条消息给队列

这里写图片描述

2 查看队列中的消息数为2

这里写图片描述

3 消费消息

这里写图片描述

4 查看消费之后的消息
这里写图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页