{"id":19756808,"url":"https://github.com/imiphp/imi-grpc","last_synced_at":"2025-04-30T12:30:45.345Z","repository":{"id":50454477,"uuid":"225538626","full_name":"imiphp/imi-grpc","owner":"imiphp","description":"在 imi 框架中集成 gRPC 服务开发、客户端调用及连接池","archived":false,"fork":false,"pushed_at":"2024-05-07T04:59:54.000Z","size":314,"stargazers_count":9,"open_issues_count":0,"forks_count":4,"subscribers_count":4,"default_branch":"2.0","last_synced_at":"2024-05-23T02:34:06.543Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/imiphp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-12-03T05:32:00.000Z","updated_at":"2024-05-28T11:13:03.886Z","dependencies_parsed_at":"2023-01-30T17:45:26.498Z","dependency_job_id":"d2d39fb4-c330-440a-8ef1-d7788c3bca71","html_url":"https://github.com/imiphp/imi-grpc","commit_stats":{"total_commits":74,"total_committers":4,"mean_commits":18.5,"dds":0.04054054054054057,"last_synced_commit":"b7d85fae5aafaaac3bda401eb8aafc87a611ca9a"},"previous_names":[],"tags_count":57,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imiphp%2Fimi-grpc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imiphp%2Fimi-grpc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imiphp%2Fimi-grpc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/imiphp%2Fimi-grpc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/imiphp","download_url":"https://codeload.github.com/imiphp/imi-grpc/tar.gz/refs/heads/2.0","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224119584,"owners_count":17258906,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-12T03:16:58.898Z","updated_at":"2024-11-12T03:16:59.659Z","avatar_url":"https://github.com/imiphp.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# imi-grpc\n\n[![Latest Version](https://img.shields.io/packagist/v/imiphp/imi-grpc.svg)](https://packagist.org/packages/imiphp/imi-grpc)\n[![Php Version](https://img.shields.io/badge/php-%3E=7.4-brightgreen.svg)](https://secure.php.net/)\n[![Swoole Version](https://img.shields.io/badge/swoole-%3E=4.1.0-brightgreen.svg)](https://github.com/swoole/swoole-src)\n[![IMI License](https://img.shields.io/github/license/imiphp/imi-grpc.svg)](https://github.com/imiphp/imi-grpc/blob/master/LICENSE)\n\n## 介绍\n\n在 imi 框架中集成 gRPC 服务开发、客户端调用及连接池。\n\n通讯协议为二进制的 Protobuf。\n\n\u003e 本仓库仅用于浏览，不接受 issue 和 Pull Requests，请前往：\u003chttps://github.com/imiphp/imi\u003e\n\n## Composer\n\n本项目可以使用composer安装，遵循psr-4自动加载规则，在你的 `composer.json` 中加入下面的内容:\n\n```json\n{\n    \"require\": {\n        \"imiphp/imi-grpc\": \"~2.0.0\"\n    }\n}\n```\n\n然后执行 `composer update` 安装。\n\n## 使用说明\n\n可以参考 `example` 目录示例，包括完整的服务端和客户端调用。\n\n### 服务和消息格式定义\n\ngRPC 和 Protobuf 是黄金搭档，Protobuf 是用来做通讯消息格式的序列化和反序列化的工作。\n\ngRPC 通讯有请求（Request）消息和响应（Response）消息，从请求消息中获取请求参数，通过响应消息返回给客户端。\n\n定义参考：`example/grpc/grpc.proto`\n\n```proto\nsyntax = \"proto3\";\n\npackage grpc;\noption php_generic_services = true;\n\nservice AuthService {\n    rpc Login (LoginRequest) returns (LoginResponse);\n}\n\nmessage LoginRequest {\n    string phone = 1;       // 手机号\n    string password = 2;    // 密码\n}\n\nmessage LoginResponse {\n    bool success = 1;       // 是否成功\n    string error = 2;       // 错误信息\n}\n```\n\n定义好后，通过命令生成 PHP 文件：`protoc --php_out=./ grpc.proto`\n\nprotoc 下载和安装：\u003chttps://github.com/protocolbuffers/protobuf/releases\u003e\n\n### 服务端\n\n在项目 `config/config.php` 中配置：\n\n```php\n[\n    'ignorePaths' =\u003e [\n        // 添加RPC忽略目录\n        \\dirname(__DIR__) . \\DIRECTORY_SEPARATOR . 'grpc',\n    ],\n]\n```\n\n如果你用主服务器：\n\n```php\n[\n    // 主服务器配置\n    'mainServer'    =\u003e  [\n        'namespace' =\u003e    'ImiApp\\GrpcServer',\n        'type'      =\u003e    'GrpcServer',\n        'host'      =\u003e    '127.0.0.1',\n        'port'      =\u003e    8080,\n    ],\n]\n```\n\n如果你用子服务器：\n\n```php\n[\n    // 子服务器（端口监听）配置\n    'subServers'    =\u003e  [\n        // 子服务器名\n        'XXX'   =\u003e  [\n            'namespace' =\u003e    'ImiApp\\GrpcServer',\n            'type'      =\u003e    'GrpcServer',\n            'host'      =\u003e    '127.0.0.1',\n            'port'      =\u003e    8080,\n        ]\n    ],\n]\n```\n\n#### 控制器\n\n写法与 Http Api 几乎一致。\n\n标准 gRPC Url 格式为：`http://host:port/{package}.{service}/{method}`\n\n```php\n/**\n * @Controller(\"/grpc.AuthService/\")\n */\nclass AuthServiceController extends HttpController implements AuthServiceInterface\n{\n    /**\n     * Method \u003ccode\u003elogin\u003c/code\u003e\n     *\n     * @Action\n     *\n     * @param \\Grpc\\LoginRequest $request\n     * @return \\Grpc\\LoginResponse\n     */\n    public function login(\\Grpc\\LoginRequest $request)\n    {\n        $response = new LoginResponse;\n        $success = '12345678901' === $request-\u003egetPhone() \u0026\u0026 '123456' === $request-\u003egetPassword();\n        $response-\u003esetSuccess($success);\n        $response-\u003esetError($success ? '' : '登录失败');\n        return $response;\n    }\n\n}\n```\n\n### 客户端\n\n#### 连接池配置\n\n```php\n[\n    // 连接池配置\n    'pools'    =\u003e    [\n        'grpc'  =\u003e  [\n            'async'    =\u003e    [\n                'pool'    =\u003e    [\n                    'class'        =\u003e    \\Imi\\Rpc\\Client\\Pool\\RpcClientCoroutinePool::class,\n                    'config'    =\u003e    [\n                        // 根据实际情况设置\n                        'maxResources'  =\u003e    100,\n                        'minResources'  =\u003e    1,\n                    ],\n                ],\n                'resource'    =\u003e    [\n                    // 这里需要和你的服务端路由一致\n                    'url'           =\u003e  'http://127.0.0.1:8080/{package}.{service}/{name}',\n                    // 'url'           =\u003e  'http://127.0.0.1:8080/{package}.{service}/{name|ucfirst}', // 参数支持设定函数处理，比如这个将方法名首字母大写，兼容其它部分语言\n                    'clientClass'   =\u003e  \\Imi\\Grpc\\Client\\GrpcClient::class,\n                    'method'        =\u003e  'POST', // 指定请求方式，默认 GET\n                    'timeout'       =\u003e  30, // 超时时间，单位：秒\n                ]\n            ],\n        ],\n    ],\n    'rpc'   =\u003e  [\n        'defaultPool'   =\u003e  'grpc',\n    ],\n]\n```\n\n### 客户端调用\n\n代码调用：\n\n```php\n// $service = \\Imi\\Rpc\\Client\\Pool\\RpcClientPool::getInstance('连接池名')-\u003egetService('服务名', '生成出来的服务接口类名');\n$service = \\Imi\\Rpc\\Client\\Pool\\RpcClientPool::getInstance()-\u003egetService('AuthService', \\Grpc\\AuthServiceInterface::class);\n$request = new \\Grpc\\LoginRequest;\n$request-\u003esetPhone('');\n$service-\u003elogin($request);\n```\n\n注解调用：\n\n```php\nuse Imi\\Rpc\\Annotation\\RpcClient;\nuse Imi\\Grpc\\Client\\Annotation\\GrpcService;\n\nclass Test\n{\n    /**\n     * @RpcClient()\n     *\n     * @var \\Imi\\Rpc\\Client\\IRpcClient\n     */\n    protected $rpcClient;\n\n    /**\n     * @GrpcService(serviceName=\"grpc.AuthService\", interface=\\Grpc\\AuthServiceInterface::class)\n     *\n     * @var \\Grpc\\AuthServiceInterface\n     */\n    protected $authService;\n\n    public function aaa()\n    {\n        $request = new \\Grpc\\LoginRequest;\n        $request-\u003esetPhone('');\n\n        // 方法一\n        $this-\u003erpcClient-\u003egetService('服务名', '生成出来的服务接口类名')-\u003e方法名($request);\n\n        // 方法二\n        $this-\u003exxxRpc-\u003e方法名($request);\n    }\n}\n```\n\n`@GrpcService` 注解的 `serviceName` 属性格式为 `{package}.{service}`；\n`interface` 属性是生成出来的服务接口类名\n\n**↓↓↓注意↓↓↓：**\n\n\u003e 使用 `@GrpcService` 注解注入时，如果调用的 `grpc` 接口方法名是：`getName`、`send`、`recv`、`call`、`getClient`，请使用 `call` 方法来调用，因为这和内置方法名相冲突了。\n\n## 免费技术支持\n\nQQ群：17916227 [![点击加群](https://pub.idqqimg.com/wpa/images/group.png \"点击加群\")](https://jq.qq.com/?_wv=1027\u0026k=5wXf4Zq)，如有问题会有人解答和修复。\n\n## 运行环境\n\n- [PHP](https://php.net/) \u003e= 7.4\n- [Composer](https://getcomposer.org/) \u003e= 2.0\n- [Swoole](https://www.swoole.com/) \u003e= 4.7.0\n\n## 版权信息\n\n`imi-grpc` 遵循 MIT 开源协议发布，并提供免费使用。\n\n## 捐赠\n\n\u003cimg src=\"https://raw.githubusercontent.com/imiphp/imi/2.0/res/pay.png\"/\u003e\n\n开源不求盈利，多少都是心意，生活不易，随缘随缘……\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimiphp%2Fimi-grpc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fimiphp%2Fimi-grpc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fimiphp%2Fimi-grpc/lists"}