Categorytrpc.group/trpc-go/trpc-codec/grpc
modulepackage
1.0.0
Repository: https://github.com/trpc-ecosystem/go-codec.git
Documentation: pkg.go.dev

# README

tRPC-Go grpc protocol

BK Pipelines Status Coverage GoDoc The tRPC-Go framework achieves the purpose of supporting the grpc protocol through package introduction and grpc server encapsulation. It supports grpc server to process grpc client requests through grpc server transport and codec.

Quick start

The following is the creation of a sample demo to demonstrate the usage process.

Suppose our current business project app is test, and the service server we want to develop is hellogrpc.

The git project used is http://git.woa.com/trpc-go/trpc-codec.git, and this example is placed under the grpc/examples path under the project.

During the operation, you can set your own app and server name, but you need to pay attention to the replacement of the corresponding fields in the subsequent steps.

Preparation

  1. An environment with a golang compilation environment (golang 1.11 or later).
  2. Install trpc tool
  3. Install grpc_cli tool

Start

  1. clone project: git clone "http://git.woa.com/trpc-go/trpc-codec.git"

  2. cd trpc-codec/grpc/examples

  3. mkdir hellogrpc && cd hellogrpc && mkdir protocol

  4. init golang mod:go mod init git.code.oa.com/trpc-go/trpc-codec/grpc/examples/hellogrpc

  5. On the protocol path, write the service agreement file vim protocol/hellogrpc.proto

syntax = "proto3";  
package trpc.app.server;
option go_package="trpc.group/trpc-go/trpc-codec/grpc/testdata/protocols/streams";

message Req {
  string msg = 1;
}

message Rsp {
  string msg = 1;
}

service Greeter {
  rpc Hello(Req) returns (Rsp) {}
  rpc GetStream (Req) returns (stream Rsp){}
  rpc PutStream (stream Req) returns (Rsp){}
  rpc AllStream (stream Req) returns (stream Rsp){}
}
> **Pay attention to the definition of package and go_package in proto, for details, please refer to [tRPC-Go Code of Conduct](https://iwiki.oa.tencent.com/pages/viewpage.action?pageId=99485634). **

6. Generate a serving model via the command line: trpc create --protocol=grpc --protofile=protocol/hellogrpc.proto --output .. !!!Note: Please use the trpc command line tool of v0.3.17 and later versions to enable grpc protocol support. If you want to use the trpc library to implement the grpc client, please use the trpc command line tool of v0.4.1 and later versions. 7. In order to facilitate testing, replace the remote protocol with local go mod edit -replace=git.code.oa.com/trpc-go/trpc-codec/grpc/examples/hellogrpc/protocol=./stub/git.code.oa.com/trpc-go/trpc-codec/grpc/examples/hellogrpc/protocol

  1. Write business logic:

    • Modify main.go, add trpc-grpc package, and register in the main function:

      It will be modified to be directly supported by the trpc tool in the future, and it needs to be manually introduced and registered for the time being

      // Import library files
      import "git.code.oa.com/trpc-go/trpc-codec/grpc"
      ...
      func main() {
      
      	s := trpc.NewServer()
      
      	pb.RegisterGreeterService(s, &greeterServiceImpl{})
      
      	s.Serve()
      }
      
    • Modify the greeter.go file of the service interface, as follows:

      // Package main is the main package.
      package main
      
      import (
      	"context"
      
      	pb "trpc.group/trpc-go/trpc-codec/grpc/examples/hellogrpc/protocol"
      )
      
      // SayHello ...
      func (s *greeterServiceImpl) SayHello(ctx context.Context, req *pb.HelloRequest, rsp *pb.HelloReply) error {
      	// implement business logic here ...
      	// new content
      	rsp.Msg = "hello grpc client: " + req.Msg
      
      	return nil
      }
      
      // SayHi ...
      func (s *greeterServiceImpl) SayHi(ctx context.Context, req *pb.HelloRequest, rsp *pb.HelloReply) error {
      	// implement business logic here ...
      	// new content
      	rsp.Msg = "hi grpc client: " + req.Msg
      
      	return nil
      }
      
  2. Compile: go build, will generate the executable file of hellogrpc.

  3. Modify the protocol field under service in the startup configuration trpc_go.yaml file under the current path, from trpc to grpc:

  service:                                     # The service provided by the business service can have multiple
      - name: trpc.test.hellogrpc.Greeter      # service route name
        ip: 127.0.0.1                          # The service listens to the ip address. You can use the placeholder ${ip}, choose one of ip and nic, and give priority to ip
        #nic: eth0
        port: 8000                             # Service listening port can use placeholder ${port}
        network: tcp                           # Network monitoring type tcp/udp
        protocol: grpc                         # Change to grpc
        timeout: 1000                          # Request maximum processing time, at milliseconds
  1. Start the service: ./hellogrpc &

  2. Execute tests with grpc-cli:

    # view service
    $ grpc_cli ls localhost:8000
    grpc.reflection.v1alpha.ServerReflection
    trpc.test.hellogrpc.Greeter
    
    # View details of the Greeter service
    $ grpc_cli ls localhost:8000 trpc.test.hellogrpc.Greeter -l
    filename: hellogrpc.proto
    package: trpc.test.hellogrpc;
    service Greeter {
      rpc SayHello(trpc.test.hellogrpc.HelloRequest) returns (trpc.test.hellogrpc.HelloReply) {}
      rpc SayHi(trpc.test.hellogrpc.HelloRequest) returns (trpc.test.hellogrpc.HelloReply) {}
    }
    
    # See the details of the Greeter.SayHi method
    $ grpc_cli ls localhost:8000 trpc.test.hellogrpc.Greeter.SayHi -l
    rpc SayHi(trpc.test.hellogrpc.HelloRequest) returns (trpc.test.hellogrpc.HelloReply) {}
    
    # Debug Greeter.SayHi interface
    $ grpc_cli call localhost:8000 'trpc.test.hellogrpc.Greeter.SayHi' "msg: 'I am a test.'"
    msg: "hi grpc client: I am a test."
    Rpc succeeded with OK status
    
  3. Write client code Client code generated using grpc-go.

# Generate client code for grpc-go
$ protoc --go_out=plugins=grpc:. protocol/hellogrpc.proto

You can also use trpc to write client code, please use v0.4.1 and above trpc-go-cmdline to generate client stub code, refer to example/client/tgrpc to implement the client.

  1. Use the grpc-stream method See example for details

Problem statement

Related References

grpc protocol http2 frame Full analysis of grpc protocol unpacking process grpc protocol codec implementation

# Packages

No description provided by the author

# Functions

NewServerStreamTransport Create grpc_stream transport.
NewServerTransport create transport.
NewStreamClient Generate a new StreamClient.
ParseGRPCMetadata Called by the trpc-go server to obtain the metadata of the client.
Register All external routes used to statically register grpc service, and the mapping of the return type.
RegisterStream Register grpc stream description information Keep the previous RegisterMethod method, which can be collected later.
StreamHandler Encapsulate trpc.Handler as grpcHandler.
WithHeader trpc-go client call, set the md sent to the server, or accept the md from the server.
WithServerGRPCMetadata Called by the trpc-go server to send metadata.

# Variables

ContextKeyHeader key in context to store Header.
DefaultClientCodec Default client codec.
DefaultClientTransport default client communication layer.
DefaultServerCodec Default codec instance.
DefaultServerStreamTransport default server stream transport.
DefaultServerTransport : Construct and encapsulate the grpc server transport instance.
DefaultStreamClient Generate a new StreamClient.

# Structs

ClientCodec is the codec for the grpc client, does nothing.
GrpcToTrpcLayer implements GrpcToTrpcer and offers a handler of grpc server.
Header stored in context to communicate with trpc.
RegisterInfo grpc Information required for registration.
RegisterMethodsInfo Register the content of the method.
RegisterStreamsInfo Register the content of the stream.
ServerCodec Server codec.
ServerStreamTransport transport layer.
ServerTransport transport layer.
StreamClient grpc.Stream client implementation.

# Interfaces

GrpcToTrpcer is an interface to represent handler of grpc server.