• rabbimq 生产消费者


    composer.json

    {
        "require": {
            "php-amqplib/php-amqplib": "^2.9"
        }
    }
    

    composer update

      

    publish.php

    <?php
    
    require_once "./vendor/autoload.php";
    
    use PhpAmqpLibConnectionAMQPStreamConnection;
    use PhpAmqpLibMessageAMQPMessage;
    
    
    $conf = [
        'host' => '192.168.33.50',
        'port' => 5672,
        'user' => 'admin',
        'pwd' => 'admin',
        'vhost' => '/',
    ];
    
    $exchangeName = 'ttt'; //交换机名
    $queueName = 'ttt'; //队列名称
    $routingKey = 'ttt'; //路由关键字(也可以省略)
    
    $conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
        $conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']
    );
    $channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
    
    
    $channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
    $channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
    $channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字
    
    
    
    $msgBody = json_encode(["name" => "iGoo", "age" => 22]);
    $msg = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'delivery_mode' => 2]); //生成消息
    $r = $channel->basic_publish($msg, $exchangeName, $routingKey); //推送消息到某个交换机
    $channel->close();
    $conn->close();
    

      consumer.php

    <?php
    
    require_once __DIR__ . '/vendor/autoload.php';
    use PhpAmqpLibConnectionAMQPStreamConnection;
    
    $connection = new AMQPStreamConnection('192.168.33.50', 5672, 'admin', 'admin');
    $channel = $connection->channel();
    
    $exchangeName = 'ttt'; //交换机名
    $queueName = 'ttt'; //队列名称
    $routingKey = 'ttt'; //路由关键字(也可以省略)
    
    $channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
    $channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
    $channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字
    
    
    echo ' [*] Waiting for messages. To exit press CTRL+C', "
    ";
    $callback = function($msg) {
        echo " [x] Received ", $msg->body, "
    ";
    };
    $channel->basic_consume('ttt', '', false, true, false, false, $callback);
    while(count($channel->callbacks)) {
        $channel->wait();
    }
    
    $channel->close();
    $connection->close();
    
    
    ?>
  • 相关阅读:
    Python基础综合练习
    熟悉常用的Linux操作
    大数据概述
    C语言简易文法(无左递归)
    自动机
    C语言简易文法
    词法分析实验报告
    词法分析
    综合练习:词频统计
    组合数据类型综合练习
  • 原文地址:https://www.cnblogs.com/brady-wang/p/11168490.html
Copyright © 2020-2023  润新知