Swoole 协程与高性能 PHP 开发
Swoole 让 PHP 支持协程,大幅提升 IO 密集型场景性能。
1. 安装
pecl install swoole2. 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 带入高性能领域。
