美文网首页
rabbitmq 简单模式

rabbitmq 简单模式

作者: 该死的金箍 | 来源:发表于2024-04-17 10:04 被阅读0次

//生产者 代码【在构造函数中进行了连接操作 析构函数使用关闭连接操作】

public function jianDan()
{
    $this->channel->queue_declare('hello', false, false, false, false);
    $data = [
        'id' =>100
    ];
    $msg  =new AMQPMessage(json_encode($data));
    $this->channel->basic_publish($msg, '', 'hello');
    echo " [x] Sent 'Hello World!'\n";
}

//消费者代码  我这里使用的TP6框架的console

protected function execute(Input$input, Output$output)
{
     $this->connection =new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
     $this->channel    =$this->connection->channel();
     $this->channel->queue_declare('hello', false, false, false, false);

    echo " [*] Waiting for messages. To exit press CTRL+C\n";
    $callback =function ($msg) {
        echo date("Y-m-d H:i:s");
        $body =json_decode($msg->getBody(), true);
        $id  =$body['id'];
        print_r(app(MqTestController::class)->userInfo($id));
    };
    $this->channel->basic_consume('hello', '', false, true, false, false, $callback);//自动ack
    try {
        $this->channel->consume();
    }catch (\Throwable$exception) {
        echo $exception->getMessage();
    }
    $this->channel->close();
    $this->connection->close();
}

每次生产者进行消息投递
如果消费者未开启 
那么可以通过rabbitMq的管理面板进行查看队列情况

通过命令 php think 查看console 配置是否成功

然后执行 php think TestMq 然后消费者会一直挂起 只要有消息投递 就会接收到消息

相关文章

网友评论

      本文标题:rabbitmq 简单模式

      本文链接:https://www.haomeiwen.com/subject/ayvsxjtx.html