欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

Swoole 协程与高性能 PHP 开发

时间:2026年08月12日 05:38:48 浏览:0

Swoole 协程与高性能 PHP 开发


Swoole 让 PHP 支持协程,大幅提升 IO 密集型场景性能。


1. 安装


pecl install swoole

2. HTTP 服务器


use Swoole\Http\Server;

$server = new Server('0.0.0.0', 9501);
$server->on('request', function ($request, $response) {
$response->header('Content-Type', 'application/json');
$response->end(json_encode(['message' => 'Hello Swoole']));
});
$server->start();

3. 协程并发请求


use Swoole\Coroutine;
use Swoole\Coroutine\Http\Client;

Coroutine\run(function () {
$urls = ['http://httpbin.org/get', 'http://httpbin.org/ip'];
$wg = new Coroutine\WaitGroup();

foreach ($urls as $url) {
$wg->add();
Coroutine::create(function () use ($url, $wg) {
$client = new Client($url, 80);
$client->get('/');
echo $client->body;
$wg->done();
});
}
$wg->wait();
});

4. 连接池(Redis/MySQL)


使用 Swoole\Coroutine\Channel 实现连接池,复用连接,提升性能。


Swoole 将 PHP 带入高性能领域。