diff --git a/README.md b/README.md index 7c13605ef91fbacb22eabb23cf40ff0138cc2a88..66df4e101c8ad47fcda019621fb4310617b85e8b 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,86 @@ -# AdminMatrix Swoole 扩展(基于 think-swoole 二次开发) -交流群:787100169 [![点击加群](https://pub.idqqimg.com/wpa/images/group.png "点击加群")](https://jq.qq.com/?_wv=1027&k=VRcdnUKL) -## 说明 +# AdminMatrix Swoole 扩展 -本项目是基于 [think-swoole](https://github.com/top-think/think-swoole) 进行的二次开发和扩展,在原有功能基础上新增了 Gateway 服务支持。 +[English](./README.md) | 中文 -## 新增功能 +基于 [think-swoole](https://github.com/top-think/think-swoole) 二次开发的 Swoole 扩展,支持 HTTP、WebSocket、RPC 等功能,并新增了 Gateway 服务支持。 -### Gateway 服务 +## 交流群 + +[![点击加群](https://pub.idqqimg.com/wpa/images/group.png "点击加群")](https://jq.qq.com/?_wv=1027&k=VRcdnUKL) + +## 功能特性 + +### 核心功能 + +- **HTTP 服务** - 高性能 HTTP Server,支持协程风格 +- **WebSocket 服务** - 支持路由调度方式的 WebSocket 实现 +- **RPC 远程调用** - 支持 JSON 格式的 RPC 协议 +- **Gateway 服务** - 基于 GatewayWorker 架构的 WebSocket Gateway +- **热更新** - 文件修改自动重载 +- **队列支持** - 集成 think-queue + +### 新增 Gateway 服务 基于 GatewayWorker 架构实现的 WebSocket Gateway 服务,支持多 Gateway 服务配置和事件监听机制。 #### 特性 - 支持多个 Gateway 服务实例 -- GatewayWorker 风格的静态方法(sendToAll, sendToClient, isOnline 等) -- 事件监听机制(gateway.onopen, gateway.onmessage, gateway.onclose) -- 独立进程启动,避免事件循环冲突 -- 完善的配置说明和最佳实践 +- GatewayWorker 风格的静态方法 +- 事件监听机制(onopen, onmessage, onclose) +- 独立进程启动 + +## 安装 + +```bash +composer require adminmatrix/matrix_swoole +``` + +需要先安装 [swoole](https://www.swoole.com/) 扩展。 + +## 配置 -#### 配置示例 +在 `config/swoole.php` 中配置服务参数: ```php -'gateway' => [ - 'enable' => true, - 'registerAddress' => '127.0.0.1', - "resisterPort" => 1236, - "registerName" => 'websocket_register', - "registerType" => 'text', - 'services' => [ - [ - 'enable' => true, - 'name' => '聊天服务', - 'port' => 2346, - 'address' => '0.0.0.0', - 'handler' => \adminmatrix\swoole\gateway\Event::class, - 'worker_num' => 2, // 根据连接数调整 +return [ + 'gateway' => [ + 'enable' => true, + 'registerAddress' => '127.0.0.1', + 'registerPort' => 1236, + 'registerName' => 'websocket_register', + 'registerType' => 'text', + 'services' => [ + [ + 'enable' => true, + 'name' => '聊天服务', + 'port' => 2346, + 'address' => '0.0.0.0', + 'handler' => \adminmatrix\swoole\gateway\Event::class, + 'worker_num' => 2, + ], ], ], -], +]; ``` -#### Gateway 进程配置建议 +## 使用方法 -- 每个 Gateway 进程可处理 5000-10000 连接 -- 在线连接 < 10000:2 个 Gateway 进程 -- 每增加 10000 连接:增加 1 个 Gateway 进程 -- Gateway 进程过多会增加进程间通讯开销 +### 启动服务 -#### BusinessWorker 进程配置建议(完整架构中) +```bash +php think swoole +``` -- 阻塞式 IO:CPU 核心数的 1-4 倍 -- 非阻塞式 IO:CPU 核心数的 4-8 倍 +启动后默认在 `0.0.0.0:8080` 启动 HTTP Server。 -#### 使用示例 +### Gateway 使用示例 ```php +use adminmatrix\swoole\gateway\Gateway; + // 注册事件监听器 Gateway::getInstance()->on('gateway.onopen', function ($clientId, $request) { echo "客户端连接: {$clientId}\n"; @@ -67,12 +91,12 @@ Gateway::getInstance()->on('gateway.onmessage', function ($clientId, $message) { // 广播消息 Gateway::sendToAll([ 'type' => 'message', - 'from' => $clientId, + $clientId, 'content' => $message ]); }); -Gateway::getInstance()->on('gateway.onclose', function ($clientId) { +Gateway 'from' =>::getInstance()->on('gateway.onclose', function ($clientId) { echo "客户端断开: {$clientId}\n"; }); ``` @@ -85,143 +109,27 @@ Gateway::getInstance()->on('gateway.onclose', function ($clientId) { - `Gateway::getAllClientCount()` - 获取在线客户端数量 - `Gateway::getAllClientIdList()` - 获取所有在线客户端 ID 列表 -## 安装 - -安装本扩展: - -~~~ -composer require adminmatrix/matrix_swoole -~~~ - -安装 swoole 扩展。 - -## 使用方法 - -直接在命令行下启动 HTTP 服务端。 - -~~~ -php think swoole -~~~ - -启动完成后,默认会在 0.0.0.0:8080 启动一个 HTTP Server,可以直接访问当前的应用。 - -swoole 的相关参数可以在 `config/swoole.php` 里面配置(具体参考配置文件内容)。 - -如果需要使用守护进程方式运行,建议使用 supervisor 来管理进程。 - -### 启动显示 - -启动时会显示详细的服务配置信息: - -``` -═══════════════════════════════════════════════════════════ -Swoole Server Configuration -═══════════════════════════════════════════════════════════ - -+------------+-------+------+--------------------+-----------------------+-------+-------+ -| event-loop | proto | user | worker | listen | count | state | -+------------+-------+------+--------------------+-----------------------+-------+-------+ -| swoole | tcp | root | HTTP Server | http://0.0.0.0:8080 | 16 | [OK] | -| swoole | - | root | hot update | none | 1 | [OK] | -| swoole | ws | root | WebSocket Server | ws://0.0.0.0:8080 | 16 | [OK] | -| websocket | text | root | websocket_register | text://127.0.0.1:1236 | 0 | [ok] | -| gateway | ws | root | 聊天服务 | ws://0.0.0.0:2346 | 16 | [OK] | -+------------+-------+------+--------------------+-----------------------+-------+-------+ -``` - -## 访问静态文件 - -> 4.0 开始协程风格服务端默认不支持静态文件访问,建议使用 nginx 来支持静态文件访问,也可使用路由输出文件内容,下面是示例,可参照修改 - -### 1. 添加静态文件路由: - -```php -Route::get('static/:path', function (string $path) { - $filename = public_path() . $path; - return new \think\swoole\response\File($filename); -})->pattern(['path' => '.*\.\w+$']); -``` - -### 2. 访问路由 - -`http://localhost/static/文件路径` - -## 队列支持 - -> 4.0 开始协程风格服务端没有 task 进程了,使用 think-queue 代替 - -使用方法见 [think-queue](https://github.com/top-think/think-queue) - -以下配置代替 think-queue 里的最后一步:`监听任务并执行`,无需另外起进程执行队列 - -```php -return [ - // ... - 'queue' => [ - 'enable' => true, - //键名是队列名称 - 'workers' => [ - //下面参数是不设置时的默认配置 - 'default' => [ - 'delay' => 0, - 'sleep' => 3, - 'tries' => 0, - 'timeout' => 60, - 'worker_num' => 1, - ], - //使用@符号后面可指定队列使用驱动 - 'default@connection' => [ - //此处可不设置任何参数,使用上面的默认配置 - ], - ], - ], - // ... -]; -``` - -### websocket - -> 新增路由调度的方式,方便实现多个 websocket 服务 - -#### 配置 - -``` -swoole.websocket.route = true 时开启 -``` - -#### 路由定义 -```php -Route::get('path1','controller/action1'); -Route::get('path2','controller/action2'); -``` - -#### 控制器 +### WebSocket 使用 ```php use \think\swoole\Websocket; use \think\swoole\websocket\Event; use \Swoole\WebSocket\Frame; -class Controller { +Route::get('ws', 'websocket/index'); - public function action1(){//不可以在这里注入websocket对象 - +class IndexController extends Controller { + public function index() { return \think\swoole\helper\websocket() - ->onOpen(...) - ->onMessage(function(Websocket $websocket, Frame $frame){ //只可在事件响应这里注入websocket对象 - ... + ->onOpen(function(Websocket $websocket, Request $request) { + echo "WebSocket 连接打开\n"; }) - ->onClose(...); - } - - public function action2(){ - - return \think\swoole\helper\websocket() - ->onOpen(...) - ->onMessage(function(Websocket $websocket, Frame $frame){ - ... + ->onMessage(function(Websocket $websocket, Frame $frame) { + $websocket->push(['type' => 'reply', 'data' => $frame->data]); }) - ->onClose(...); + ->onClose(function(Websocket $websocket) { + echo "WebSocket 连接关闭\n"; + }); } } ``` @@ -229,16 +137,63 @@ class Controller { ### 流式输出 ```php - -class Controller { - - public function action(){ +class IndexController extends Controller { + public function stream() { return \think\swoole\helper\iterator(value(function(){ - foreach(range(1,10) as $i) + foreach(range(1, 10) as $i) { yield $i; - sleep(1);//模拟等待 + sleep(1); } })); } } -``` \ No newline at end of file +``` + +## 进程配置建议 + +### Gateway 进程 + +- 每个 Gateway 进程可处理 5000-10000 连接 +- 在线连接 < 10000:2 个 Gateway 进程 +- 每增加 10000 连接:增加 1 个 Gateway 进程 + +### BusinessWorker 进程 + +- 阻塞式 IO:CPU 核心数的 1-4 倍 +- 非阻塞式 IO:CPU 核心数的 4-8 倍 + +## 项目结构 + +``` +src/ +├── command/ # 命令行相关 +├── concerns/ # Traits 特性 +├── config/ # 配置文件 +├── contract/ # 接口定义 +├── coroutine/ # 协程工具 +├── exception/ # 异常类 +├── gateway/ # Gateway 服务 +├── helpers.php # 辅助函数 +├── ipc/ # 进程间通信 +├── listen/ # 事件监听 +├── lock/ # 分布式锁 +├── message/ # 消息类 +├── middleware/ # 中间件 +├── packet/ # 数据包处理 +├── pool/ # 连接池 +├── response/ # 响应类 +├── resetters/ # 重置器 +├── rpc/ # RPC 实现 +├── support/ # 工具支持 +├── watcher/ # 文件监控 +└── websocket/ # WebSocket 实现 +``` + +## 注意事项 + +- 4.0 版本开始协程风格服务端默认不支持静态文件访问,建议使用 nginx 处理静态文件 +- 4.0 版本没有 task 进程,使用 think-queue 代替 + +## License + +MIT License \ No newline at end of file