欢迎来到程序员中文网!

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

PHP 协程与 Swoole 高性能编程

时间:2026年08月12日 04:46:50 浏览:1

Swoole 入门


Swoole 是 PHP 的协程框架,让 PHP 可以像 Go 一样处理高并发。


pecl install swoole

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();

协程并发


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();
});

协程连接池


class RedisPool {
private $pool;
public function __construct(int $size = 10) {
$this->pool = new \Swoole\Coroutine\Channel($size);
for ($i = 0; $i < $size; $i++) {
$redis = new \Swoole\Coroutine\Redis();
$redis->connect('127.0.0.1', 6379);
$this->pool->push($redis);
}
}
public function get() {
return $this->pool->pop();
}
public function put($redis) {
$this->pool->push($redis);
}
}

Swoole 让 PHP 在 IO 密集型场景下性能媲美 Node.js 和 Go。