如果是使用自定義類 要怎么觸發(fā)workerman/http-client來發(fā)送請求獲取數(shù)據(jù)?
webman/http-client 目前不支持同步用法,用curl或者guzzle吧
guzzle支持異步請求,在webman httpServer的OnMessage回調(diào)的業(yè)務邏輯上下文內(nèi)是同步阻塞的,但可以并行發(fā)送多次請求;
插件http://wtbis.cn/plugin/50中有webman/http-client及guzzle異步請求的相關使用案例代碼;
"每個 worker 都可以在同請求建立鏈接后,請求傳輸數(shù)據(jù)期間 可以 不阻塞 的去處理其他請求" 請問等待curl返回結(jié)果的這段時間,這個worker會執(zhí)行其他請求嗎?
謝謝 我有點蒙了 之前好像看到 一個請求在讀取數(shù)據(jù)庫等待的時候 這個worker進程好像還會處理其他請求~~發(fā)送curl等待返回結(jié)果的時候,這個worker進程也會先處理其他請求嗎?然后等這個curl有結(jié)果返回,再回來處理?還是curl只是在等待返回?
代碼如下:
<?php
namespace App\api\controller;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise\Utils;
use Psr\Http\Message\ResponseInterface;
class Index
{
public function index()
{
echo 'start: ' . time() . PHP_EOL;
$client = new Client();
$promises = [];
//異步請求一
$promises[] = $client->getAsync('http://www.webman.com/test')
->then(
function (ResponseInterface $res) {
echo 'res1: ' . $res->getBody() . ' ' . time() . PHP_EOL;
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
}
);
//異步請求二
$promises[] = $client->getAsync('http://www.webman.com/test2')
->then(
function (ResponseInterface $res) {
echo 'res2: ' . $res->getBody() . ' ' . time() . PHP_EOL;
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
}
);
//等待上面兩個異步請求完成
Utils::inspectAll($promises);
return response('api index');
}
}
我之前也這樣用過,確實會提高響應時間,因為只會等待請求時間最長的那個請求
但有一種特殊情況
如果第二個請求,需要依賴第一個請求的結(jié)果,就不能這樣發(fā)送并發(fā)請求
這種并發(fā)請求,在適用于.每個請求之間,互不依賴的情況