AmpPHP 非阻塞并發(fā)框架
Amp 是一個(gè) PHP 非阻塞并發(fā)框架,它提供了一個(gè)事件循環(huán),promise 和 stream 作為異步編程的基礎(chǔ)。與生成器結(jié)合使用的 promise 用于構(gòu)建協(xié)程,它允許像同步代碼一樣編寫(xiě)異步代碼,而不需要任何回調(diào)。
demo:
<?php
use Amp\Artax\Response;
use Amp\Loop;
require __DIR__ . '/../vendor/autoload.php';
Loop::run(function () {
$uris = [
"https://google.com/",
"https://github.com/",
"https://stackoverflow.com/",
];
$client = new Amp\Artax\DefaultClient;
$client->setOption(Amp\Artax\Client::OP_DISCARD_BODY, true);
try {
foreach ($uris as $uri) {
$promises[$uri] = $client->request($uri);
}
$responses = yield $promises;
foreach ($responses as $uri => $response) {
print $uri . " - " . $response->getStatus() . $response->getReason() . PHP_EOL;
}
} catch (Amp\Artax\HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The Client::request() method itself will never throw directly, but returns a promise.
print $error->getMessage() . PHP_EOL;
}
});評(píng)論
圖片
表情
