PHPackages                             imiphp/imi-grpc - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. imiphp/imi-grpc

ActiveLibrary[API Development](/categories/api)

imiphp/imi-grpc
===============

在 imi 框架中集成 gRPC 服务开发、客户端调用及连接池

v2.1.29(2y ago)958041MulanPSL-2.0PHPCI failing

Since Dec 3Pushed 1y ago2 watchersCompare

[ Source](https://github.com/imiphp/imi-grpc)[ Packagist](https://packagist.org/packages/imiphp/imi-grpc)[ RSS](/packages/imiphp-imi-grpc/feed)WikiDiscussions 2.0 Synced today

READMEChangelog (10)Dependencies (4)Versions (62)Used By (1)

imi-grpc
========

[](#imi-grpc)

[![Latest Version](https://camo.githubusercontent.com/ea183ed70cfcb3319069fbc91a9eb277f0e0dadd7db136e069206f855b899210/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696d697068702f696d692d677270632e737667)](https://packagist.org/packages/imiphp/imi-grpc)[![Php Version](https://camo.githubusercontent.com/4a5c2ab20974058a8bab53ecb30ac4c2e6bb961df6229b7386fdc097ab53dfa8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d2533453d372e342d627269676874677265656e2e737667)](https://secure.php.net/)[![Swoole Version](https://camo.githubusercontent.com/f077644cadc3b88104d75a54818d0e1462f910dc6d6dfd9939ea295fb11b4e2b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f73776f6f6c652d2533453d342e312e302d627269676874677265656e2e737667)](https://github.com/swoole/swoole-src)[![IMI License](https://camo.githubusercontent.com/a6f076779d9b0858438d48268fc5f2d5ec0767d745eaa903e14c3bf0c86424a7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f696d697068702f696d692d677270632e737667)](https://github.com/imiphp/imi-grpc/blob/master/LICENSE)

介绍
--

[](#介绍)

在 imi 框架中集成 gRPC 服务开发、客户端调用及连接池。

通讯协议为二进制的 Protobuf。

> 本仓库仅用于浏览，不接受 issue 和 Pull Requests，请前往：

Composer
--------

[](#composer)

本项目可以使用composer安装，遵循psr-4自动加载规则，在你的 `composer.json` 中加入下面的内容:

```
{
    "require": {
        "imiphp/imi-grpc": "~2.0.0"
    }
}
```

然后执行 `composer update` 安装。

使用说明
----

[](#使用说明)

可以参考 `example` 目录示例，包括完整的服务端和客户端调用。

### 服务和消息格式定义

[](#服务和消息格式定义)

gRPC 和 Protobuf 是黄金搭档，Protobuf 是用来做通讯消息格式的序列化和反序列化的工作。

gRPC 通讯有请求（Request）消息和响应（Response）消息，从请求消息中获取请求参数，通过响应消息返回给客户端。

定义参考：`example/grpc/grpc.proto`

```
syntax = "proto3";

package grpc;
option php_generic_services = true;

service AuthService {
    rpc Login (LoginRequest) returns (LoginResponse);
}

message LoginRequest {
    string phone = 1;       // 手机号
    string password = 2;    // 密码
}

message LoginResponse {
    bool success = 1;       // 是否成功
    string error = 2;       // 错误信息
}
```

定义好后，通过命令生成 PHP 文件：`protoc --php_out=./ grpc.proto`

protoc 下载和安装：

### 服务端

[](#服务端)

在项目 `config/config.php` 中配置：

```
[
    'ignorePaths' => [
        // 添加RPC忽略目录
        \dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'grpc',
    ],
]
```

如果你用主服务器：

```
[
    // 主服务器配置
    'mainServer'    =>  [
        'namespace' =>    'ImiApp\GrpcServer',
        'type'      =>    'GrpcServer',
        'host'      =>    '127.0.0.1',
        'port'      =>    8080,
    ],
]
```

如果你用子服务器：

```
[
    // 子服务器（端口监听）配置
    'subServers'    =>  [
        // 子服务器名
        'XXX'   =>  [
            'namespace' =>    'ImiApp\GrpcServer',
            'type'      =>    'GrpcServer',
            'host'      =>    '127.0.0.1',
            'port'      =>    8080,
        ]
    ],
]
```

#### 控制器

[](#控制器)

写法与 Http Api 几乎一致。

标准 gRPC Url 格式为：`http://host:port/{package}.{service}/{method}`

```
/**
 * @Controller("/grpc.AuthService/")
 */
class AuthServiceController extends HttpController implements AuthServiceInterface
{
    /**
     * Method login
     *
     * @Action
     *
     * @param \Grpc\LoginRequest $request
     * @return \Grpc\LoginResponse
     */
    public function login(\Grpc\LoginRequest $request)
    {
        $response = new LoginResponse;
        $success = '12345678901' === $request->getPhone() && '123456' === $request->getPassword();
        $response->setSuccess($success);
        $response->setError($success ? '' : '登录失败');
        return $response;
    }

}
```

### 客户端

[](#客户端)

#### 连接池配置

[](#连接池配置)

```
[
    // 连接池配置
    'pools'    =>    [
        'grpc'  =>  [
            'async'    =>    [
                'pool'    =>    [
                    'class'        =>    \Imi\Rpc\Client\Pool\RpcClientCoroutinePool::class,
                    'config'    =>    [
                        // 根据实际情况设置
                        'maxResources'  =>    100,
                        'minResources'  =>    1,
                    ],
                ],
                'resource'    =>    [
                    // 这里需要和你的服务端路由一致
                    'url'           =>  'http://127.0.0.1:8080/{package}.{service}/{name}',
                    // 'url'           =>  'http://127.0.0.1:8080/{package}.{service}/{name|ucfirst}', // 参数支持设定函数处理，比如这个将方法名首字母大写，兼容其它部分语言
                    'clientClass'   =>  \Imi\Grpc\Client\GrpcClient::class,
                    'method'        =>  'POST', // 指定请求方式，默认 GET
                    'timeout'       =>  30, // 超时时间，单位：秒
                ]
            ],
        ],
    ],
    'rpc'   =>  [
        'defaultPool'   =>  'grpc',
    ],
]
```

### 客户端调用

[](#客户端调用)

代码调用：

```
// $service = \Imi\Rpc\Client\Pool\RpcClientPool::getInstance('连接池名')->getService('服务名', '生成出来的服务接口类名');
$service = \Imi\Rpc\Client\Pool\RpcClientPool::getInstance()->getService('AuthService', \Grpc\AuthServiceInterface::class);
$request = new \Grpc\LoginRequest;
$request->setPhone('');
$service->login($request);
```

注解调用：

```
use Imi\Rpc\Annotation\RpcClient;
use Imi\Grpc\Client\Annotation\GrpcService;

class Test
{
    /**
     * @RpcClient()
     *
     * @var \Imi\Rpc\Client\IRpcClient
     */
    protected $rpcClient;

    /**
     * @GrpcService(serviceName="grpc.AuthService", interface=\Grpc\AuthServiceInterface::class)
     *
     * @var \Grpc\AuthServiceInterface
     */
    protected $authService;

    public function aaa()
    {
        $request = new \Grpc\LoginRequest;
        $request->setPhone('');

        // 方法一
        $this->rpcClient->getService('服务名', '生成出来的服务接口类名')->方法名($request);

        // 方法二
        $this->xxxRpc->方法名($request);
    }
}
```

`@GrpcService` 注解的 `serviceName` 属性格式为 `{package}.{service}`； `interface` 属性是生成出来的服务接口类名

**↓↓↓注意↓↓↓：**

> 使用 `@GrpcService` 注解注入时，如果调用的 `grpc` 接口方法名是：`getName`、`send`、`recv`、`call`、`getClient`，请使用 `call` 方法来调用，因为这和内置方法名相冲突了。

免费技术支持
------

[](#免费技术支持)

QQ群：17916227 [![点击加群](https://camo.githubusercontent.com/75b53e353bb9e5064662e185a6d39f4bb88c4e45bd3a1240ddf599525edb6afa/68747470733a2f2f7075622e69647171696d672e636f6d2f7770612f696d616765732f67726f75702e706e67 "点击加群")](https://jq.qq.com/?_wv=1027&k=5wXf4Zq)，如有问题会有人解答和修复。

运行环境
----

[](#运行环境)

- [PHP](https://php.net/) &gt;= 7.4
- [Composer](https://getcomposer.org/) &gt;= 2.0
- [Swoole](https://www.swoole.com/) &gt;= 4.7.0

版权信息
----

[](#版权信息)

`imi-grpc` 遵循 MIT 开源协议发布，并提供免费使用。

捐赠
--

[](#捐赠)

[![](https://raw.githubusercontent.com/imiphp/imi/2.0/res/pay.png)](https://raw.githubusercontent.com/imiphp/imi/2.0/res/pay.png)

开源不求盈利，多少都是心意，生活不易，随缘随缘……

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance27

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor1

Top contributor holds 96.1% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~26 days

Total

62

Last Release

733d ago

Major Versions

v1.1.2 → v2.0.02021-08-20

v1.1.3 → v2.0.22021-10-13

v2.1.28 → 3.0.x-dev2024-05-02

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f917bb42280d114c53cebadc2942a13ee03abe14971089f88895e266d637169?d=identicon)[Yurunsoft](/maintainers/Yurunsoft)

---

Top Contributors

[![Yurunsoft](https://avatars.githubusercontent.com/u/20104656?v=4)](https://github.com/Yurunsoft "Yurunsoft (73 commits)")[![0HG0](https://avatars.githubusercontent.com/u/46053324?v=4)](https://github.com/0HG0 "0HG0 (1 commits)")[![mrlovables](https://avatars.githubusercontent.com/u/16332777?v=4)](https://github.com/mrlovables "mrlovables (1 commits)")[![NHZEX](https://avatars.githubusercontent.com/u/14545600?v=4)](https://github.com/NHZEX "NHZEX (1 commits)")

### Embed Badge

![Health badge](/badges/imiphp-imi-grpc/health.svg)

```
[![Health](https://phpackages.com/badges/imiphp-imi-grpc/health.svg)](https://phpackages.com/packages/imiphp-imi-grpc)
```

###  Alternatives

[google/gax

Google API Core for PHP

263103.1M453](/packages/google-gax)[google/grpc-gcp

gRPC GCP library for channel management

18497.8M3](/packages/google-grpc-gcp)[google/common-protos

Google API Common Protos for PHP

173103.7M49](/packages/google-common-protos)[googleads/google-ads-php

Google Ads API client for PHP

3497.6M9](/packages/googleads-google-ads-php)[temporal/sdk

Temporal SDK

4002.2M18](/packages/temporal-sdk)[agence104/livekit-server-sdk

Server-side SDK for LiveKit.

79189.9k1](/packages/agence104-livekit-server-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
