PHP协程实战:构建高并发IO密集型应用
一、性能对比
协程模式使并发能力提升1000倍,内存占用仅为传统方式的1/10
// 传统同步模式:100并发需要100个进程
// 协程模式:10000并发只需1个进程
二、基础概念
1. 协程创建
use SwooleCoroutine;
Coroutine::create(function() {
$result = Coroutine::gethostbyname('example.com');
echo "DNS解析结果: $result";
});
2. 协程通信
$channel = new CoroutineChannel(10);
Coroutine::create(function() use ($channel) {
$channel->push(['data' => '消息内容']);
});
Coroutine::create(function() use ($channel) {
$data = $channel->pop();
print_r($data);
});
三、高级应用
1. 协程HTTP客户端
Coroutine::create(function() {
$cli = new CoroutineHttpClient('api.example.com', 443, true);
$cli->setHeaders(['Host' => 'api.example.com']);
$cli->get('/data');
echo $cli->body;
});
2. 协程MySQL连接池
$pool = new CoroutineMySQLPool([
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'root',
'password' => '',
'database' => 'test',
'max_conn' => 50
]);
Coroutine::create(function() use ($pool) {
$conn = $pool->get();
$result = $conn->query('SELECT * FROM users');
$pool->put($conn);
print_r($result);
});
四、完整案例
实时聊天服务
$server = new SwooleWebSocketServer('0.0.0.0', 9501);
$server->on('Message', function($server, $frame) {
// 广播消息给所有客户端
foreach ($server->connections as $fd) {
if ($server->isEstablished($fd)) {
$server->push($fd, $frame->data);
}
}
});
$server->on('Request', function($request, $response) {
// HTTP接口获取在线人数
$response->header('Content-Type', 'application/json');
$response->end(json_encode([
'count' => count($server->connections)
]));
});
$server->start();
function runDemo() {
alert(‘需要安装Swoole扩展运行示例代码:pecl install swoole’);
}