在控制器中使用RabbitMQ消息

时间:2018-11-29 14:27:13

标签: php laravel rabbitmq amqp

我目前正在学习有关服务,API和AMQP消息传递系统(准确地说是RabbitMQ)的信息,我正在关注关于RabbitMQ消息传递的tutorial。我已经完成了所有工作,但是我想更改项目中的某些内容。我想从路由和控制器中调用发布者和使用者脚本,而不是在终端中键入它们( php src / publisher.php php src / consumer.php

首先,我创建了两条路线:

 Route::get('/send-message', 'ServiceAController@index');
 Route::get('/receive-message', 'ServiceBController@index');

第一个路由(发送消息)用于将HTTP请求作为消息发送到RabbitMQ,这是通过邮递员POST请求完成的,我在其中插入了所需的参数。该路由的控制器工作正常,看起来像这样:

public function index(Request $request){
    //Returning status 200 and sending message if amount is in range
    if( (-100000000  <= $request->amount )  &&  ($request->amount <= 100000000 )){
        //Sending message to RabbitMQ
        $amount = $request->amount;
        $currency = $request->currency;

        //Saving request data to variable to publish it
        $messageContent = json_encode([
            'amount' => $amount * 100,
            'currency' => $currency,
        ]);

        //Sending broker message
        $host = 'secret';
        $port = 5672;
        $user = 'secret';
        $pass = 'secret';
        $vhost = 'secret';
        $exchange = 'balance';
        $queue = 'local_balance';

        $connection = new AMQPStreamConnection($host, $port, $user, $pass, $vhost);
        $channel = $connection->channel();
        /*
            The following code is the same both in the consumer and the producer.
            In this way we are sure we always have a queue to consume from and an
                exchange where to publish messages.
        */
        /*
            name: $queue
            passive: false
            durable: true // the queue will survive server restarts
            exclusive: false // the queue can be accessed in other channels
            auto_delete: false //the queue won't be deleted once the channel is closed.
        */
        $channel->queue_declare($queue, false, true, false, false);
        /*
            name: $exchange
            type: direct
            passive: false
            durable: true // the exchange will survive server restarts
            auto_delete: false //the exchange won't be deleted once the channel is closed.
        */
        $channel->exchange_declare($exchange, 'direct', false, true, false);
        $channel->queue_bind($queue, $exchange);
        $messageBody = $messageContent;
        $message = new AMQPMessage($messageBody, ['content_type' => 'application/json', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
        $channel->basic_publish($message, $exchange);
        $channel->close();
        $connection->close();

        //Returning json response of HTTP payload
        $response = json_encode([
            'amount' => +number_format($amount, 2, '.', ''),
            'currency' => $currency,
        ]);
        return $response;
    }else{
        //Returning status 400 if amount is not in acceptable range
        abort(400, 'Amount is not in acceptable range'); //Returning code 400 if condition isn't met
    }
}

但是,当我将消费者代码放入ServiceBController时,我的问题就开始了,就像我为上一个代码所做的一样。我的ServiceBController看起来像这样:

public function index(){

    $host = 'secret';
    $port = 5672;
    $user = 'secret';
    $pass = 'secret';
    $vhost = 'secret';
    $exchange = 'balance';
    $queue = 'local_balance';

    $connection = new AMQPStreamConnection($host, $port, $user, $pass, $vhost);
    $channel = $connection->channel();
    /*
        The following code is the same both in the consumer and the producer.
        In this way we are sure we always have a queue to consume from and an
            exchange where to publish messages.
    */
    /*
        name: $queue
        passive: false
        durable: true // the queue will survive server restarts
        exclusive: false // the queue can be accessed in other channels
        auto_delete: false //the queue won't be deleted once the channel is closed.
    */
    $channel->queue_declare($queue, false, true, false, false);
    /*
        name: $exchange
        type: direct
        passive: false
        durable: true // the exchange will survive server restarts
        auto_delete: false //the exchange won't be deleted once the channel is closed.
    */
    $channel->exchange_declare($exchange, 'direct', false, true, false);
    $channel->queue_bind($queue, $exchange);
    /**
     * @param AMQPMessage $message
     */
    function process_message(AMQPMessage $message){
        $messageBody = json_decode($message->body);
        $amount = $messageBody->amount;
        $currency = $messageBody->currency;

        file_put_contents('C:/xampp/htdocs/nsoft/data' . '.json', $message->body);

        $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
    }
    /*
        queue: Queue from where to get the messages
        consumer_tag: Consumer identifier
        no_local: Don't receive messages published by this consumer.
        no_ack: Tells the server if the consumer will acknowledge the messages.
        exclusive: Request exclusive consumer access, meaning only this consumer can access the queue
        nowait:
        callback: A PHP Callback
    */
    $consumerTag = 'local.consumer';
    $channel->basic_consume($queue, $consumerTag, false, false, false, false, 'process_message');
    /**
     * @param \PhpAmqpLib\Channel\AMQPChannel $channel
     * @param \PhpAmqpLib\Connection\AbstractConnection $connection
     */
    function shutdown($channel, $connection){
        $channel->close();
        $connection->close();
    }

    register_shutdown_function('shutdown', $channel, $connection);

    while (count($channel->callbacks)) {
        $channel->wait();
    }
}

在Postman中调用它并获得请求后,出现以下错误:

  

Symfony \ Component \ Debug \ Exception \ FatalErrorException:文件C:\ xampp \ htdocs \ nsoft \ vendor \ php-amqplib \ php-amqplib \ PhpAmqpLib \ Wire \ IO \ StreamIO.php中的最大执行时间超过了30秒在第227行。

我已经被这个错误困扰了几天,似乎找不到解决方案,所以我需要别人的帮助。我在这里做错了什么?作为参考,当我将其作为一个单独的文件( src / consumer.php )以及通过终端调用它时,相同的使用者脚本将起作用。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

max_execution_time中更改参数php.ini的值

max_execution_time = 360   ;Execution time in seconds

答案 1 :(得分:0)

我可以建议您使用Laravel的RabbitMQ队列驱动程序:

https://github.com/vyuldashev/laravel-queue-rabbitmq

使用RabbitMQ服务器,您可以通过Laravel的本机队列系统管理所有消息。 (配置后)唯一需要做的就是在控制台中运行php artisan queue:work

有几种方法可以使用来处理队列的即时工作。例如,您可以使用Supervisor:

http://supervisord.org/