AmpPHP 非阻塞并发框架

联合创作 · 2023-09-29 13:59

Amp 是一个 PHP 非阻塞并发框架,它提供了一个事件循环,promise 和 stream 作为异步编程的基础。与生成器结合使用的 promise 用于构建协程,它允许像同步代码一样编写异步代码,而不需要任何回调。


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;
}
});
浏览 20
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑 分享
举报