【无标题】RabbitMQ+Swoole多进程消费

producer.php

<?php
try {
    // 1.建立连接
    $connection = new AMQPConnection([
        'host' => '127.0.0.1',
        'port' => 5672,
        'vhost' => '/',
        'login' => 'guest',
        'password' => 'guest'
    ]);
    $connection->connect();
 
    // 2.建立通道
    $channel = new AMQPChannel($connection);
    // 3.创建交换机
    $exchange = new AMQPExchange($channel);
    $exchangeName = 'trade';
    $exchange->setName($exchangeName);
    $exchange->setType(AMQP_EX_TYPE_DIRECT);
    $exchange->declareExchange();
 
    // 5.绑定路由关系发送消息
    $data = [
        'tid' => uniqid(),
        'msg' => 'trade'
    ];
 
    $routingKey = '/trade';
    $exchange->publish(json_encode($data));
 
} catch (Exception $e) {
    echo $e->getMessage();
 
}

consumer.php

<?php
 
 
$workerNum = 4; // 一般为CPU核数的4倍
// 进程池
$pool = new Swoole\Process\Pool($workerNum);
// 多进程,共享一个连接
$pool->on('WorkerStart', function($pool, $workerId) {
    // 子进程空间
 
    echo "WorkerId {$workerId} is started \n";
 
    try {
        // 1.建立连接
        $connection = new AMQPConnection([
            'host' => '127.0.0.1',
            'port' => 5672,
            'vhost' => '/',
            'login' => 'guest',
            'password' => 'guest'
        ]);
 
        $connection->connect();
        // 2.建立通道
        $channel = new AMQPChannel($connection);
        // 3.创建队列
        $queueName = 'trade';
        $queue = new AMQPQueue($channel);
        $queue->setName('trade');
        $queue->declareQueue();
 
        $data = [
            'tid' => uniqid(),
            'msg' => 'trade'
        ];
 
        $routingKey = '/trade';
 
        // 4.绑定路由监听
        $exchangeName = 'trade';
        $queue->bind($exchangeName, $routingKey);
        // 阻塞状态,有数据时才会执行
        $queue->consume(function($envelope, $queue) use ($workerId) {
            // ack 应答机制
            // 查看那个进程在消费
            var_dump($workerId, $envelope->getBody());
            $queue->ack($envelope->getDeliveryTag());
        });
 
    } catch (Exception $e) {
        echo $e->getMessage();
 
    }
 
});
 
// 进程关闭
$pool->on('WorkerStop', function($pool, $workerId) {
    echo "WorkerId {$workerId} is stoped\n";
});

————————————————
版权声明:本文为CSDN博主「深漂小码哥」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq2942713658/article/details/119698065

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值