playtini/grpc-server-bundle

使用 spriral/php-grpc 创建 gRPC 服务器

1.0.0 2021-07-30 11:18 UTC

This package is auto-updated.

Last update: 2024-09-10 16:36:02 UTC


README

使用 spriral/php-grpc 创建 gRPC 服务器

安装步骤

步骤 1: 下载软件包

$ composer require playtini/grpc-server-bundle

步骤 2: 将服务器二进制文件复制到 ./project/bin 文件夹

./vendor/playtini/grpc-server-bundle/bin/rr-grpc ./project/bin/

步骤 3: 在项目根目录下创建服务器配置 .rr.yaml

grpc:
  listen: "tcp://:6096"
  proto: "./proto/base.proto"
  workers:
    command: "./bin/console roadrunner:grpc-worker"
    relay: "unix://var/roadrunner.sock"
    pool:
      numWorkers: 1

limit:
  interval: 1
  services:
    grpc:
      maxMemory: 100
      TTL: 0
      idleTTL: 0
      execTTL: 60

使用示例

创建 *.proto

base.proto

syntax="proto3";

package playtini;

option php_generic_services = true;
option php_namespace = "Playtini\\MainServiceName";
option php_metadata_namespace = "Playtini\\MainServiceName\\Meta";

import 'calculator.proto';

calculator.proto

syntax = "proto3";

package playtini.calculator;

option php_namespace = "Playtini\\MainServiceName\\Calculator";
option php_metadata_namespace = "Playtini\\MainServiceName\\Meta";

message Sum {
  int32 a = 1;
  int32 b = 2;
}

message Result {
  int32 result = 1;
}

service Calculator {
  rpc Sum (calculator.Sum) returns (calculator.Result);
}

生成服务

使用 protocprotoc-gen-grpc 插件(roadrunner 自定义插件)生成服务

protoc /proto/base.proto \
        -I/proto -I/proto/base.proto proto/calculator.proto \
        --php_out=/proto/src \
        $(: 👇 custom plugin from roadrunner to generate server interface) \
        --php-grpc_out=/proto/src \
        $(: 👇 generates the client code) \
        --grpc_out=/proto/src \
        --plugin=protoc-gen-grpc=/protobuf/grpc/bins/opt/grpc_php_plugin \
        --proto_path /proto

创建服务器端代码

实现生成的接口

<?php

namespace App\Calculator;

use Playtini\MainServiceName\Calculator\CalculatorInterface;
use Playtini\MainServiceName\Calculator\Result;
use Playtini\MainServiceName\Calculator\Sum;
use Spiral\GRPC;

class CalculatorService implements CalculatorInterface
{
    public function Sum(GRPC\ContextInterface $ctx, Sum $in): Result
    {
        return new Result([
            'result' => $in->getA() + $in->getB(), 
        ]);
    }
}

添加到 service.yaml

services:
    App\Calculator\CalculatorService:
        tags: ['playtini.roadrunner.grpc_service']

运行服务器

bin/rr-grpc serve -v -d

帮助

spriral/php-grpc - 在 RoadRunner 之上构建的高性能 PHP GRPC 服务器。

相关文章和源代码