如果是使用自定義類 要怎么觸發(fā)workerman/http-client來發(fā)送請(qǐng)求獲取數(shù)據(jù)?
webman/http-client 目前不支持同步用法,用curl或者guzzle吧
guzzle支持異步請(qǐng)求,在webman httpServer的OnMessage回調(diào)的業(yè)務(wù)邏輯上下文內(nèi)是同步阻塞的,但可以并行發(fā)送多次請(qǐng)求;
插件http://m.wtbis.cn/plugin/50中有webman/http-client及guzzle異步請(qǐng)求的相關(guān)使用案例代碼;
"每個(gè) worker 都可以在同請(qǐng)求建立鏈接后,請(qǐng)求傳輸數(shù)據(jù)期間 可以 不阻塞 的去處理其他請(qǐng)求" 請(qǐng)問等待curl返回結(jié)果的這段時(shí)間,這個(gè)worker會(huì)執(zhí)行其他請(qǐng)求嗎?
謝謝 我有點(diǎn)蒙了 之前好像看到 一個(gè)請(qǐng)求在讀取數(shù)據(jù)庫等待的時(shí)候 這個(gè)worker進(jìn)程好像還會(huì)處理其他請(qǐng)求~~發(fā)送curl等待返回結(jié)果的時(shí)候,這個(gè)worker進(jìn)程也會(huì)先處理其他請(qǐng)求嗎?然后等這個(gè)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 = [];
//異步請(qǐng)求一
$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";
}
);
//異步請(qǐng)求二
$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";
}
);
//等待上面兩個(gè)異步請(qǐng)求完成
Utils::inspectAll($promises);
return response('api index');
}
}
我之前也這樣用過,確實(shí)會(huì)提高響應(yīng)時(shí)間,因?yàn)橹粫?huì)等待請(qǐng)求時(shí)間最長的那個(gè)請(qǐng)求
但有一種特殊情況
如果第二個(gè)請(qǐng)求,需要依賴第一個(gè)請(qǐng)求的結(jié)果,就不能這樣發(fā)送并發(fā)請(qǐng)求
這種并發(fā)請(qǐng)求,在適用于.每個(gè)請(qǐng)求之間,互不依賴的情況