当前位置: 首页 > news >正文

Yii2-Swoole 快速入门 - dacheng

Yii2-Swoole 快速入门

让你的 Yii2 应用性能提升 10-100 倍!本教程将教你如何在 yii2-app-basic 中快速集成 yii2-swoole。

为什么使用 yii2-swoole?

  • ⚡ 比 PHP-FPM 快 10-100 倍
  • 🔄 数据库和 Redis 连接池自动管理
  • 🚀 协程并发处理请求
  • 💻 代码几乎不需要修改

系统要求

  • PHP >= 8.1
  • Swoole >= 6.0
  • Yii2 >= 2.0

安装 Swoole

pecl install swoole

php.ini 中添加:

extension=swoole.so

验证:

php --ri swoole

快速开始

1. 安装扩展

composer require dacheng-php/yii2-swoole

2. 创建配置文件

创建 config/swoole.php

<?phpreturn ['bootstrap' => [['class' => \Dacheng\Yii2\Swoole\Bootstrap::class,'componentId' => 'swooleHttpServer','memoryLimit' => '2G',],],'components' => ['swooleHttpServer' => ['class' => \Dacheng\Yii2\Swoole\Server\HttpServer::class,'host' => '127.0.0.1','port' => 9501,'documentRoot' => __DIR__ . '/../web','settings' => ['max_coroutine' => 100000,'log_level' => SWOOLE_LOG_WARNING,],'dispatcher' => new \Dacheng\Yii2\Swoole\Server\RequestDispatcher(__DIR__ . '/web.php'),],],
];

3. 修改 Web 配置

编辑 config/web.php,在 return $config; 之前添加:

// 合并 Swoole 配置
$swooleConfig = require __DIR__ . '/swoole.php';
$config = \yii\helpers\ArrayHelper::merge($swooleConfig, $config);

4. 启动服务器

php yii swoole/start

访问 http://127.0.0.1:9501 即可!

停止服务器:

php yii swoole/stop
# 或按 Ctrl+C

进阶功能

数据库连接池

config/swoole.php 中添加:

'db' => ['class' => \Dacheng\Yii2\Swoole\Db\CoroutineDbConnection::class,'dsn' => 'mysql:host=127.0.0.1;dbname=your_database','username' => 'root','password' => '','charset' => 'utf8mb4','poolMaxActive' => 20,'poolWaitTimeout' => 5.0,
],

使用方式与标准 Yii2 完全相同,连接池自动管理。

Redis 连接池

composer require yiisoft/yii2-redis

config/swoole.php 中添加:

'redis' => ['class' => \Dacheng\Yii2\Swoole\Redis\CoroutineRedisConnection::class,'hostname' => '127.0.0.1','port' => 6379,'poolMaxActive' => 20,'poolWaitTimeout' => 5.0,
],'cache' => ['class' => \Dacheng\Yii2\Swoole\Cache\CoroutineRedisCache::class,'redis' => 'redis',
],'session' => ['class' => \Dacheng\Yii2\Swoole\Session\CoroutineSession::class,'redis' => 'redis',
],

异步队列

composer require yiisoft/yii2-queue

配置:

'bootstrap' => [// ...'queue',
],
'components' => ['queue' => ['class' => \Dacheng\Yii2\Swoole\Queue\CoroutineRedisQueue::class,'redis' => 'redis','channel' => 'queue','concurrency' => 10,],
],

创建任务 jobs/EmailJob.php

<?php
namespace app\jobs;class EmailJob extends \yii\base\BaseObject implements \yii\queue\JobInterface
{public $to;public $subject;public function execute($queue){// 发送邮件\Yii::$app->mailer->compose()->setTo($this->to)->setSubject($this->subject)->send();}
}

使用:

Yii::$app->queue->push(new EmailJob(['to' => 'user@example.com','subject' => '测试',
]));

协程 HTTP 客户端

配置:

'httpClient' => ['class' => \Dacheng\Yii2\Swoole\HttpClient\CoroutineClient::class,'transport' => ['class' => \Dacheng\Yii2\Swoole\HttpClient\CoroutineTransport::class,],
],

使用:

// 单个请求
$response = Yii::$app->httpClient->get('https://api.example.com/users')->send();// 批量并发请求
$requests = ['users' => Yii::$app->httpClient->get('https://api.example.com/users'),'posts' => Yii::$app->httpClient->get('https://api.example.com/posts'),
];
$responses = Yii::$app->httpClient->batchSend($requests);

完整配置

config/swoole.php 示例:

<?phpreturn ['bootstrap' => [['class' => \Dacheng\Yii2\Swoole\Bootstrap::class,'componentId' => 'swooleHttpServer',],'queue',],'components' => ['swooleHttpServer' => ['class' => \Dacheng\Yii2\Swoole\Server\HttpServer::class,'host' => '127.0.0.1','port' => 9501,'documentRoot' => __DIR__ . '/../web','dispatcher' => new \Dacheng\Yii2\Swoole\Server\RequestDispatcher(__DIR__ . '/web.php'),],'db' => ['class' => \Dacheng\Yii2\Swoole\Db\CoroutineDbConnection::class,'dsn' => 'mysql:host=127.0.0.1;dbname=myapp','username' => 'root','password' => '','poolMaxActive' => 20,],'redis' => ['class' => \Dacheng\Yii2\Swoole\Redis\CoroutineRedisConnection::class,'hostname' => '127.0.0.1','poolMaxActive' => 20,],'cache' => ['class' => \Dacheng\Yii2\Swoole\Cache\CoroutineRedisCache::class,'redis' => 'redis',],'session' => ['class' => \Dacheng\Yii2\Swoole\Session\CoroutineSession::class,'redis' => 'redis',],'queue' => ['class' => \Dacheng\Yii2\Swoole\Queue\CoroutineRedisQueue::class,'redis' => 'redis',],],
];

常见问题

代码修改后不生效?
重启服务器:Ctrl+C 停止后重新启动(Swoole 常驻内存)

无法启动?

  • 检查 Swoole 是否安装:php --ri swoole
  • 检查端口占用:lsof -i:9501

连接超时?
增加 poolMaxActivepoolWaitTimeout 参数

静态文件 404?
确认 documentRoot 指向正确的 web 目录

生产部署

Systemd 服务

创建 /etc/systemd/system/yii2-app.service

[Unit]
Description=Yii2 Swoole
After=network.target[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/my-app
ExecStart=/usr/bin/php /var/www/my-app/yii swoole/start
Restart=on-failure[Install]
WantedBy=multi-user.target

启动:

sudo systemctl daemon-reload
sudo systemctl enable yii2-app
sudo systemctl start yii2-app

Nginx 反向代理

server {listen 80;server_name example.com;location / {proxy_pass http://127.0.0.1:9501;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}
}

注意事项

  • ⚠️ 避免使用全局变量(多请求共享)
  • ⚠️ 使用协程安全组件(CoroutineSession、CoroutineUser)
  • ⚠️ 代码修改需要重启服务器

了解更多

  • 项目主页:https://github.com/dacheng-php/yii2-swoole
  • 示例代码:查看 examples/ 目录
  • Swoole 文档:https://wiki.swoole.com/zh-cn/

如果本项目对你有帮助,欢迎 ⭐ Star!

http://icebutterfly214.com/news/7/

相关文章: