当前位置: 首页 > 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://www.zskr.cn/news/31705.html

相关文章:

  • 18 10.17
  • 17 10.16
  • 19 10.20
  • 2025年定制贯通货架厂家权威推荐榜:工业仓储智能解决方案与耐用性深度解析,精选实力厂家!
  • 2025年纺织仓库货架厂家推荐排行榜,重型货架,中型货架,阁楼货架,自动化立体仓库货架公司精选
  • ubuntu系统配置root用户
  • 2025.10.27+7[未完]
  • 2025年口罩机厂家权威推荐榜单,全自动口罩机器,全自动KN95口罩机,高效智能生产线与稳定产能保障精选
  • 2025年天金冈货架厂家权威推荐榜:重型货架,阁楼货架,仓储货架,自动化立库货架专业制造商实力解析
  • Tlias系统实战
  • Launcher 桌面源码笔记二
  • 2025年定制多层重型货架厂家推荐排行榜,仓库货架,重型仓储货架,阁楼货架,立体库货架公司精选
  • 2025年定制钢平台货架厂家推荐排行榜,阁楼式钢平台货架,重型钢平台货架,仓储钢平台货架,定制钢平台货架公司精选
  • 2025年口碑好的公司注册代理记账外包
  • 2025年热门的目视化规划落地最新推荐榜单集团
  • 2025年定制纺织重型货架厂家推荐排行榜,仓库重型货架,工业重型货架,仓储重型货架,阁楼重型货架公司推荐
  • 2025年热门的logo VI设计实力公司
  • 2025年质量好的房屋检测鉴定用户好评榜
  • 2025年口碑好的云南房屋加固服务推荐
  • 2025年比较好的水渠成型机厂家最新热销排行
  • 2025年窄巷道货架厂家权威推荐榜:定制仓储解决方案专家,高效空间利用率与耐用性深度解析
  • 2025年质量好的恒温恒湿智能柜优质厂家推荐榜单
  • 2025年热门的硅酸铝纤维陶瓷纤维毯最新TOP品牌厂家排行
  • 2025年质量好的钢结构厂家最新权威推荐排行榜
  • 2025年专业的316不锈钢网片实力厂家TOP推荐榜
  • 2025年优秀的PVC防撞碳晶板厂家最新TOP实力排行
  • 2025年流利重型货架厂家推荐排行榜,仓库流利式货架,重型流利条货架,仓储物流重型货架公司精选
  • 2025年优秀的车铣复合数控机床厂家推荐及采购参考
  • 2025年比较好的碳钢风管加工厂家最新热销排行
  • 2025人力资源/派遣/外包/劳务外包/培训服务推荐榜:广州精典人才创新领衔,招聘 / 测评 / 灵活用工优质机构精选