php rabbitmq demo

composer安装php rabbitmq包

新建composer.json文件,composer install 安装

{
    "require": {
        "php-amqplib/php-amqplib": ">=2.6.1"
    }
}

创建config.php文件

<?php
return [
    'vendor' => [
        'path' => './vendor'
    ],
    'rabbitmq' => [
        'host' => '127.0.0.1',
        'port' => '5672',
        'login' => 'guest',
        'password' => 'guest',
        'vhost' => '/'
    ]
];
?>

 

创建消费者 rabbit_consumer.php,注意具体文件引用的路径

<?php

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

$config = require "./config.php";
require_once $config['vendor']['path'] . '/autoload.php';

$connection = new AMQPStreamConnection($config['rabbitmq']['host'], $config['rabbitmq']['port'],
    $config['rabbitmq']['login'], $config['rabbitmq']['password'], $config['rabbitmq']['vhost']);
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);
$callback = function($msg) {
  echo $msg->body;
  file_put_contents('log.txt', $msg->body);
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while(true) {
    $channel->wait();
}
$channel->close();
$connection->close();

?>

 

创建生产者 rabbit_pulisher.php

<?php



$config = require "./config.php";

require_once $config['vendor']['path'] . '/autoload.php';

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

$connection = new AMQPStreamConnection($config['rabbitmq']['host'], $config['rabbitmq']['port'],
    $config['rabbitmq']['login'], $config['rabbitmq']['password'], $config['rabbitmq']['vhost']);
$channel = $connection->channel();

//发送方其实不需要设置队列, 不过对于持久化有关,建议执行该行
$channel->queue_declare('hello', false, false, false, false);

$msg = new AMQPMessage('Hello World!123'.time());
$channel->basic_publish($msg, '', 'hello');

echo " [x] Sent 'Hello World!x'\n";

$channel->close();
$connection->close();
?>

 

首先运行消费者

php rabbit_consumer.php

另起窗口运行生产者 

php rabbit_publisher.php

posted @ 2018-12-11 11:01  飞翔的贺兰猪  阅读(196)  评论(0编辑  收藏  举报