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' => DachengYii2SwooleBootstrap::class,            'componentId' => 'swooleHttpServer',            'memoryLimit' => '2G',        ],    ],    'components' => [        'swooleHttpServer' => [            'class' => DachengYii2SwooleServerHttpServer::class,            'host' => '127.0.0.1',            'port' => 9501,            'documentRoot' => __DIR__ . '/../web',            'settings' => [                'max_coroutine' => 100000,                'log_level' => SWOOLE_LOG_WARNING,            ],            'dispatcher' => new DachengYii2SwooleServerRequestDispatcher(                __DIR__ . '/web.php'            ),        ],    ],];

3. 修改 Web 配置

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

// 合并 Swoole 配置$swooleConfig = require __DIR__ . '/swoole.php';$config = yiihelpersArrayHelper::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' => DachengYii2SwooleDbCoroutineDbConnection::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' => DachengYii2SwooleRedisCoroutineRedisConnection::class,    'hostname' => '127.0.0.1',    'port' => 6379,    'poolMaxActive' => 20,    'poolWaitTimeout' => 5.0,],'cache' => [    'class' => DachengYii2SwooleCacheCoroutineRedisCache::class,    'redis' => 'redis',],'session' => [    'class' => DachengYii2SwooleSessionCoroutineSession::class,    'redis' => 'redis',],

异步队列

composer require yiisoft/yii2-queue

配置:

'bootstrap' => [    // ...    'queue',],'components' => [    'queue' => [        'class' => DachengYii2SwooleQueueCoroutineRedisQueue::class,        'redis' => 'redis',        'channel' => 'queue',        'concurrency' => 10,    ],],

创建任务 jobs/EmailJob.php

<?phpnamespace appjobs;class EmailJob extends yiibaseBaseObject implements yiiqueueJobInterface{    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' => '[email protected]',    'subject' => '测试',]));

协程 HTTP 客户端

配置:

'httpClient' => [    'class' => DachengYii2SwooleHttpClientCoroutineClient::class,    'transport' => [        'class' => DachengYii2SwooleHttpClientCoroutineTransport::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' => DachengYii2SwooleBootstrap::class,            'componentId' => 'swooleHttpServer',        ],        'queue',    ],    'components' => [        'swooleHttpServer' => [            'class' => DachengYii2SwooleServerHttpServer::class,            'host' => '127.0.0.1',            'port' => 9501,            'documentRoot' => __DIR__ . '/../web',            'dispatcher' => new DachengYii2SwooleServerRequestDispatcher(__DIR__ . '/web.php'),        ],        'db' => [            'class' => DachengYii2SwooleDbCoroutineDbConnection::class,            'dsn' => 'mysql:host=127.0.0.1;dbname=myapp',            'username' => 'root',            'password' => '',            'poolMaxActive' => 20,        ],        'redis' => [            'class' => DachengYii2SwooleRedisCoroutineRedisConnection::class,            'hostname' => '127.0.0.1',            'poolMaxActive' => 20,        ],        'cache' => [            'class' => DachengYii2SwooleCacheCoroutineRedisCache::class,            'redis' => 'redis',        ],        'session' => [            'class' => DachengYii2SwooleSessionCoroutineSession::class,            'redis' => 'redis',        ],        'queue' => [            'class' => DachengYii2SwooleQueueCoroutineRedisQueue::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 SwooleAfter=network.target[Service]Type=simpleUser=www-dataWorkingDirectory=/var/www/my-appExecStart=/usr/bin/php /var/www/my-app/yii swoole/startRestart=on-failure[Install]WantedBy=multi-user.target

启动:

sudo systemctl daemon-reloadsudo systemctl enable yii2-appsudo 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!

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:[email protected]