最近一直在探索php的异步支持,目前实现异步的扩展和框架有不少,比如swoole、workerman、raectphp等等,但不能在传统mvc使用,只能以控制台的形式编写服务.?
前两天看到php官方的php8.1版本核心加入了fiber?,虽然是是一个非常底层的API,这对于php 协程原生级语法的支持是个利好,而amphp v3?基于fiber进行封装的依赖框架?有自己的事件驱动,异步i/o等
以 amphp/http-client??组件为例 进行并发请求 下面为示例代码?
use Amp\Http\Client\HttpClientBuilder;
use Amp\Http\Client\HttpException;
use Amp\Http\Client\Request;
use function Amp\async;
use function Amp\await;
require __DIR__ . '/../.helper/functions.php';
$uris = [
"http://127.0.0.1/",
"https://github.com/",
"https://stackoverflow.com/",
];
// Instantiate the HTTP client
$client = HttpClientBuilder::buildDefault();
$requestHandler = static function (string $uri) use ($client): string {
$response = $client->request(new Request($uri));
return $response->getBody()->buffer();
};
try {
$promises = [];
foreach ($uris as $uri) {
$promises[$uri] = async($requestHandler, $uri);
}
$bodies = await($promises);
foreach ($bodies as $uri => $body) {
print $uri . " - " . \strlen($body) . " bytes" . PHP_EOL;
}
} catch (HttpException $error) {
// If something goes wrong Amp will throw the exception where the promise was yielded.
// The HttpClient::request() method itself will never throw directly, but returns a promise.
echo $error;
}
我同时请求本地和服务器的域名 使用sleep进行阻塞5s?总共执行5s就返回了结果。如果使用同步编码的方式进行请求 会花费10s的时间,由此可见? 以上代码进行了异步的请求
先简单到这里,因为php8.1?还没有正式发布不能用在生产环境中,如果有同学想进行测试 ? 需要切换到php8.1 点击跳转 下载?php8.1测试版?
composer? 要2.0以上的版本 以下是需要的依赖库 大家可以复制到 composer.json文件中
{
"require": {
"amphp/amp": "v3.*@dev",
"amphp/byte-stream": "v2.*@dev",
"amphp/sync": "v2.*@dev",
"amphp/cache": "v2.*@dev",
"amphp/process": "v2.*@dev",
"amphp/windows-registry": "v1.*@dev",
"amphp/dns": "v2.*@dev",
"amphp/socket": "v2.*@dev",
"amphp/http-client": "v5.*@dev"
}
}
|