php 异步实现
PHP 异步实现方法
PHP 本身是同步阻塞的语言,但可以通过一些扩展和库实现异步编程。以下是几种常见的实现方式:
使用 Swoole 扩展
Swoole 是 PHP 的一个高性能异步网络通信引擎,提供了协程、TCP/UDP/HTTP 服务器等异步功能。
安装 Swoole:
pecl install swoole
示例代码:
$server = new Swoole\Http\Server("0.0.0.0", 9501);
$server->on("Request", function($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World\n");
});
$server->start();
使用 ReactPHP
ReactPHP 是一个事件驱动的非阻塞 I/O 库,可以实现异步编程。
安装 ReactPHP:
composer require react/http
示例代码:

$loop = React\EventLoop\Factory::create();
$server = new React\Http\Server($loop, function (Psr\Http\Message\ServerRequestInterface $request) {
return new React\Http\Message\Response(
200,
array('Content-Type' => 'text/plain'),
"Hello World!\n"
);
});
$socket = new React\Socket\Server('0.0.0.0:8080', $loop);
$server->listen($socket);
$loop->run();
使用 AMPHP
AMPHP 是另一个异步编程库,基于协程和 Promise。
安装 AMPHP:
composer require amphp/http-server
示例代码:
Amp\Loop::run(function () {
$server = new Amp\Http\Server\Server(
[new Amp\Http\Server\RequestHandler\CallableRequestHandler(function (
Amp\Http\Server\Request $request
): Amp\Http\Server\Response {
return new Amp\Http\Server\Response(200, [
"content-type" => "text/plain",
], "Hello, World!");
})],
new Amp\Http\Server\Options(),
Loop::get()
);
yield $server->start();
Loop::run();
});
使用 PHP 原生 PCNTL 扩展
PCNTL 扩展可以创建子进程实现并行处理。

示例代码:
$pid = pcntl_fork();
if ($pid == -1) {
die('Could not fork');
} else if ($pid) {
// Parent process
pcntl_wait($status);
} else {
// Child process
echo "Child process\n";
exit;
}
使用 Gearman 实现任务队列
Gearman 是一个分布式任务分发系统,可以实现异步任务处理。
安装 Gearman:
pecl install gearman
示例代码:
$client = new GearmanClient();
$client->addServer();
$client->doBackground("reverse", "Hello World!");
注意事项
- Swoole 需要安装扩展,性能最好但环境依赖较强
- ReactPHP 和 AMPHP 是纯 PHP 实现,兼容性更好
- PCNTL 只能用于 CLI 模式,不适合 Web 环境
- Gearman 适合分布式任务处理场景
选择哪种方式取决于具体需求:
- 高性能网络服务:Swoole
- 简单异步任务:ReactPHP/AMPHP
- 后台任务处理:Gearman
- 进程控制:PCNTL






