Async requests in php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Asynchronous cURL library for PHP with reasonable API

MartinMajor/async-request

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

Asynchronous cURL library for PHP with reasonable API.

PHP is by default single-thread language but when it comes to HTTP requests it is not very convenient to do them in serial. cURL implementation in PHP offers functions for multi requests but with terrible C-style API. This library wraps those functions into modern object-oriented event-driven API.

async-request/async-request version 1.x requires PHP 7.1+ with cUrl extension enabled.

If you are using PHP5.4+ you can use async-request/async-request version 0.x.

You can easily install the newest version using Composer:

composer require async-request/async-request
$urls = [ 'http://www.example.com', 'http://www.example.org', ]; $asyncRequest = new AsyncRequest\AsyncRequest(); foreach ($urls as $url) < $request = new AsyncRequest\Request($url); $asyncRequest->enqueue($request, function(AsyncRequest\Response $response) < echo $response->getBody() . "\n"; >); > $asyncRequest->run();

You can specify number of requests that can run in parallel:

$asyncRequest->setParallelLimit(5);

You can add other requests in callback function:

$callback = function(AsyncRequest\Response $response, AsyncRequest\AsyncRequest $asyncRequest) < $asyncRequest->enqueue(new AsyncRequest\Request('http://www.example.com')); >;

You can specify priority of each request and requests with higher priority will be called first:

$asyncRequest->enqueueWithPriority(10, $request, $callback);

If you want to use some cURL options, it is as easy as this:

$request = new AsyncRequest\Request($url); $request->setOption(CURLOPT_POST, true);

And if you want some special behavior or some additional data in Response , you can always create your own Request object by implementing IRequest interface.

Читайте также:  Css mix blend mode background

About

Asynchronous cURL library for PHP with reasonable API

Источник

How to make asynchronous HTTP requests in PHP ?

Asynchronous HTTP request helps us to process HTTP requests using non-blocking input or output, in different threads. Some refer to it as COMET capabilities. The main use of Asynchronous HTTP requests is when the client is requesting the server for a late response. A common example is an AJAX chat client where we push or pull from both the client and the server. These scenarios block the client for quiet a long time on the server’s socket waiting for a new message.

PHP serves requests synchronously. It means that each line of code executes in the synchronous manner of the script. After getting the result from one line it executes next line or wait for the result before jumping to the execution of the next line of code. There are cases where we are supposed to make requests to URLs and they do not rely on each other. In this scenario we do not want to wait for the result from one request to execute other requests. Therefore, we make asynchronous requests.

Guzzle 6: Guzzle is a PHP HTTP client helps to send the HTTP requests.These methods can be used to send the asynchronous HTTP requests.

  • RequestAsync,
  • SendAsync,
  • GetAsync,
  • HeadAsync,
  • PutAsync,
  • PostAsync,
  • DeleteAsync,
  • patchAsync

Download Guzzle php package.Can be installed through composer.

php composer.phar require guzzlehttp/guzzle:~6.0
composer require guzzlehttp/guzzle:~6.0

Please include the “autoload” file in the script part of the code so that it loads all the classes and methods.

PHP

In the above code, the “autoload” file is included, and then the Guzzle Http client object is created which is stored in the “client” variable and for each Http request getAsync() method is used with the URL. The request getting the first response will print the number. The order of the request will not matter.

Asynchronous HTTP requests using Promise: A single result of an asynchronous operation represents a Promise. Asynchronous requests are used in the non-blocking of the HTTP operations. When asynchronous HTTP requests send a promise, it gets returned.

Читайте также:  Java paint set color

Execute a request using HTTPlug:

$request = $messageFactory->createRequest( 'GET', 'http://php-http.org'); $promise = $client->sendAsyncRequest($request); echo 'Non-blocking!';

Wait: The “promise” which is returned from the above, implements http\Promise\Promise. The response is not known yet during this point of time. Wait for that response to arrive.

try < $response = $promise->wait(); > catch (\Exception $exception) < echo $exception->getMessage(); >

Then: Instead of waiting, we can perform steps asynchronously. Call the then method with two arguments.

  1. One callback that will be executed if the request turns out to be successful.
  2. Callback that will be executed if the request results in an error.

// Success Callback function (ResponseInterface $response) < echo 'New response!'; // Write status code to the log file file_put_contents('responses.log', $response->getStatusCode() . «\n», FILE_APPEND); return $response; >, // Failure Callback function (\Exception $exception)

Concurrency in Promise: Concurrency means multiple computations taking place at the same time. It is good when we deal with a lot of request at the same time. For concurrency, we must use “EachPromise” class and yield generator and at last add wait() to the end of the program.

Источник

Как делать асинхронные HTTP-запросы в PHP?

Асинхронный HTTP-запрос помогают нам обрабатывать HTTP-запросы с использованием неблокирующего ввода или вывода в разных потоках. Некоторые называют это возможностями COMET . Основное использование асинхронных HTTP-запросов — это когда клиент запрашивает у сервера поздний ответ. Типичным примером является клиент чата AJAX , в котором мы отправляем или извлекаем данные как с клиента, так и с сервера. Эти сценарии блокируют клиента на длительное время в сокете сервера в ожидании нового сообщения.

PHP обслуживает запросы синхронно. Это означает, что каждая строка кода выполняется синхронно сценария. После получения результата из одной строки он выполняет следующую строку или ожидает результата, прежде чем перейти к выполнению следующей строки кода. Есть случаи, когда мы должны делать запросы к URL-адресам, а они не полагаются друг на друга. В этом сценарии мы не хотим ждать результата одного запроса для выполнения других запросов. Поэтому мы делаем асинхронные запросы.

Библиотека Guzzle 6

Guzzle — это HTTP-клиент на PHP, который помогает отправлять HTTP-запросы. Эти методы могут использоваться для отправки асинхронных HTTP-запросов.

  • RequestAsync,
  • SendAsync,
  • GetAsync,
  • HeadAsync,
  • PutAsync,
  • PostAsync,
  • DeleteAsync,
  • patchAsync

Скачайте пакет guzzle . Его можно установить через composer .

php composer.phar require guzzlehttp/guzzle:~6.0 
composer require guzzlehttp/guzzle:~6.0 

Включите файл autoload.php в часть кода сценария, чтобы он загружал все классы и методы.

getAsync('http://localhost') ->then(function ($response) < echo '10'; >), $client->getAsync('http://www.google.com') ->then(function ($response) < echo '20'; >), $client->getAsync('http://localhost') ->then(function ($response) < echo '30'; >), $client->getAsync('http://localhost') ->then(function ($response) < echo '40'; >), $client->getAsync('http://localhost') ->then(function ($response) < echo '50'; >), $client->getAsync('http://localhost') ->then(function ($response) < echo '60'; >), $client->getAsync('http://localhost') ->then(function ($response) < echo '70'; >), ]; $results = GuzzleHttp\Promise\unwrap($promises); // Please wait for a while to complete // the requests(some of them may fail) $results = GuzzleHttp\Promise\settle( $promises)->wait(); print "finish/over." . PHP_EOL; ?> 

В приведенный выше код включается файл autoload.php , а затем создается клиентский объект GuzzleHttp, который сохраняется в переменной client , и для каждого запроса Http используется метод getAsync() с URL-адресом.
Запрос, получивший первый ответ, выведет номер. Порядок запроса не имеет значения.

Читайте также:  Таблица в центре окна

Асинхронные HTTP-запросы с использованием Promise

При использовании Promise результат асинхронной операции представляет собой Promise (специальный объект, который содержит своё состояние). Асинхронные запросы используются для неблокирующих операций HTTP. Когда асинхронные HTTP-запросы отправляют Promise, то возвращается состояние.

Выполним запрос с помощью HTTPlug:

$request = $messageFactory->createRequest( 'GET', 'http://php-http.org'); $Promise = $client->sendAsyncRequest ($request); echo 'Неблокирующий!'; 

«Promise», который возвращается из вышеупомянутого, реализует http\Promise\Promise .

$promise->wait() будет ожидать получения ответа

try < $response = $promise->wait(); > catch (\Exception $exception) < echo $exception->getMessage(); > 

Вместо ожидания мы можем выполнять шаги асинхронно. Для этого нужно вызвать метод then с двумя аргументами.

  1. Функция обратного вызова, которая будет выполнена, если запрос окажется успешным.
  2. Функция обратного вызова, которая будет выполнена, если запрос приведет к ошибке.
// Success Callback function (ResponseInterface $response) < echo 'New response!'; // Write status code to the log file file_put_contents('responses.log', $response->getStatusCode() . "\n", FILE_APPEND); return $response; >, // Failure Callback function (\Exception $exception)

Параллелизм в Promise

Параллелизм означает одновременное выполнение нескольких вычислений. Обрабатка большого количества запросов одновременно может улучшить производительность. Для параллелизма мы должны использовать класс EveryPromise и генератор yield и, наконец, добавить wait() в конец программы.

getAsync( 'https://api.demo.com/v1/users?username=' . $user); > >)(); $eachPromise = new EachPromise($promises, [ // Number of concurrency 'concurrency' => 4, 'fulfilled' => function (Response $response) < if ($response->getStatusCode() == 200) < $user = json_decode( $response->getBody(), true); // processing response of the user > >, 'rejected' => function ($reason) < // handle promise rejected >]); $eachPromise->promise()->wait(); ?> 

Многопоточные запросы с cURL

PHP как правило, может обрабатывать несколько запросов. Сначала мы запускаем первый и обрабатываем ответ, затем второй и третий и так далее. Но этот процесс медленный и требует много времени. Но предлагает функции curl_multi_ * для обработки любых asnyc-запросов.

$running = null; $mh = curl_multi_init(); $ch1 = curl_init(); curl_setopt($ch1, CURLOPT_URL, ‘https://endpoint.com’); // Other curl options… curl_multi_add_handle($mh, $ch1); $ch2 = curl_init(); curl_setopt($ch2, CURLOPT_URL, ‘https://endpoint.com’); // Other curl options… curl_multi_add_handle($mh, $ch2); do < curl_multi_exec($mh, $running); curl_multi_select($mh); >while ($running > 0); $r1 = curl_multi_getcontent($ch1); $r2 = curl_multi_getcontent($ch2); curl_multi_remove_handle($mh, $ch1); curl_multi_remove_handle($mh, $ch2); curl_multi_close($mh); 

Ответы собираются в переменных «r1» и «r2». С помощью этих функций cURL мы можем запускать запросы параллельно, чтобы сэкономить время и быстрее обрабатывать ответы.

Источник

Оцените статью