2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでGuzzleを使って非同期でHTTPリクエストを投げるメモ

Posted at

非同期でHTTPリクエストができるGuzzleを試してみたメモ。
内部的にはcurl_multiを使っているそうです。

インストール

composerを使ってインストールします。

$ composer require guzzlehttp/guzzle

使い方

非同期でHTTPリクエストを投げるコードがこちら。

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;

$client = new Client();

$promises = [];
for($i = 0; $i < 10; ++$i){
    $promise = $client->requestAsync('GET', 'http://httpbin.org');
    $promise->then(
        // Fullfilled
        function(ResponseInterface $res){
            echo $res->getStatusCode() . "\n";
        },
        //Rejected 
        function(RequestException $e) {
            echo $e->getMessage() . "\n";
            echo $e->getRequest()->getMethod();
        }
    );
    $promises[] = $promise;
}
Promise\all($promises)->wait();

が、この方法だとPromiseオブジェクトがメモリを食うため、foreach()でメモリオーバーで落ちる可能性があるらしい。

この問題を回避するために使えるものが、Poolオブジェクト。
先ほどのコードをPoolオブジェクトを使う方法で書き換えたものが下記のコード。ジェネレータを使ってます。

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Promise;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;

$client = new Client();
$requests = function() use ($client) {
    for($i = 0; $i < 10; ++$i){
        yield function() use ($client) {
            $promise = $client->requestAsync('GET', 'http://httpbin.org');
            $promise->then(
                // Fullfilled
                function(ResponseInterface $res){
                    echo $res->getStatusCode() . "\n";
                },
                //Rejected 
                function(RequestException $e) {
                    echo $e->getMessage() . "\n";
                    echo $e->getRequest()->getMethod();
                }
            );
            return $promise;
        };
    }
};
$pool = new Pool($client, $requests());
$promise = $pool->promise();
$promise->wait();
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?