• 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 PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    
    $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 PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    
    $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'
    ";
    
    $channel->close();
    $connection->close();
    ?>

    首先运行消费者

    php rabbit_consumer.php

    另起窗口运行生产者 

    php rabbit_publisher.php

  • 相关阅读:
    cobalt strike
    php学习
    windows免费?linux免费?赶紧过来看吧
    python实现文件加密
    python写一个能生成三种一句话木马的脚本
    hardentools
    TensorFlow实战——个性化推荐
    对比深度学习十大框架:TensorFlow 并非最好?
    YCSB性能测试工具使用(转)
    Python文件夹与文件的操作(转)
  • 原文地址:https://www.cnblogs.com/mmmzh/p/10100993.html
Copyright © 2020-2023  润新知