user1119698
user1119698

Reputation: 157

Asynchronous request to Amazon Firehose

Is it possible to send requests to AWS asynchronously? In the real meaning.

The messages is not delivered if I'm trying to send it in a way:

      $firehose = new FirehoseClient($args);
      /** @var Promise\Promise $promise */
      $promise = $firehose->putRecordAsync($record);
      $promise->then(function ($result) {
          echo 'test';
      });

but when I add at the end of the script:

$promise->wait()

it works, but synchronously. Is there any way to make it async?

I've also tried to use a different handler:

    $curl = new CurlMultiHandler();
    $handler = HandlerStack::create($curl);
    $args = [
        'http_handler' => $handler,
        'region' => '#REGION#',
        'version' => 'latest',
        'credentials' => $credentials,
        'debug' => true
    ];
    $firehose = new FirehoseClient($args);

    while (!Promise\is_settled($promise)) {
        $curl->tick();
    }

Basically it works, but always in sync mode. What I need is to send a request to AWS and not waiting for the answer.

Upvotes: 3

Views: 1245

Answers (2)

Alexey Shokov
Alexey Shokov

Reputation: 5010

The best solution for your problem is to use an event loop implementation, like ReactPHP, for example.

Unfortunately, Guzzle (better say, cURL itself) is not compatible to work in an event loop out of the box.

Personally I've solved an equal problem by implementing a bridge to run Guzzle queries event-loop-friendly. Please, take a look at the examples.

So the code could look like this:

run(function ($loop) use ($genFn) {
    $httpHandler = new CurlMultiHandler($loop);
    $stack = HandlerStack::create($httpHandler);

    $httpClient = new Client([
        'handler' => $stack,
    ]);

    $promise = $httpClient->getAsync('https://google.com')->then(
        function ($result) { echo 'Query completed!'; },
        function ($reason) { echo 'Query failed.'; }
    );

    /*
     * The promise isn't completed yet, but the event loop will take care of it.
     * We don't need to call Promise::wait()!
     */
});

Upvotes: 1

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

I didn't work with async code in PHP but I did such things in Python.

From general understanding, you can't get any benefits of single async request surrounded by sync code. You should work in a fully async environment (i.e. you need some kind of outer event-loop). ReactPHP looks to be one of those.

Also, you can benefit from making several API requests simultaneously and wait for all them together. Like in this example http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/promises.html#executing-commands-concurrently It will work faster than making several sync calls in a row.

I hope it helps.

Upvotes: 0

Related Questions