Php使用RabbitMQ 入门小demo

廉价感情. 提交于 2019-11-25 20:52:53

1.首先需要安装PHP使用的RabbitMQ 包:php-amqplib

composer require php-amqplib/php-amqplib


php必须安装拓展:php_sockets,不然会报错:

The requested PHP extension ext-sockets * is missing from your system. Install or enable PHP's sockets extension.

2.建立服务端和客户端:

server.php

<?php
// +----------------------------------------------------------------------
// | 蜜蜂到店
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.mifengdaodian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: DB  <m18108447675@gmail.com.com>
// +----------------------------------------------------------------------
// | Date Time: 2019/11/25 10:26
// +----------------------------------------------------------------------
// | Description: rabbitMQ服务端
// +----------------------------------------------------------------------


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,我要发送的消息内容~~~'.time());

//公布消息
$channel->basic_publish($msg, '', 'hello');

//关闭通道
$channel->close();

//关闭链接
$connection->close();

 

客户端文件client.php

<?php
// +----------------------------------------------------------------------
// | 蜜蜂到店
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.mifengdaodian.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: DB  <m18108447675@gmail.com.com>
// +----------------------------------------------------------------------
// | Date Time: 2019/11/25 10:26
// +----------------------------------------------------------------------
// | Description: rabbitMQ客户端
// +----------------------------------------------------------------------


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


//闭包回调函数
$callback = function ($msg) {
    echo ' [x] Received ', $msg->body, "\n";
};

//消费队列消息
$channel->basic_consume('hello', '', false, true, false, false, $callback);


//等待消息
while ($channel->is_consuming()) {
    $channel->wait();
}

 

3.执行client.php  然后执行server.php

在clent.php就能看见server.php队列消息了

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!