grpc

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2023 License: Apache-2.0, BSD-3-Clause, MIT Imports: 20 Imported by: 7

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). **
  1. 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.

  2. 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

  3. 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
      }
      
  4. Compile: go build, will generate the executable file of hellogrpc.

  5. 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

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

Documentation

Overview

Package grpc tRPC-Go grpc 协议

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultServerCodec Default codec instance
	DefaultServerCodec = &ServerCodec{}
	// DefaultClientCodec Default client codec
	DefaultClientCodec = &ClientCodec{}
)
View Source
var ContextKeyHeader = &contextHeader{}

ContextKeyHeader key in context to store Header

View Source
var DefaultClientTransport = &clientTransport{}

DefaultClientTransport default client communication layer

View Source
var DefaultServerStreamTransport = NewServerStreamTransport()

DefaultServerStreamTransport default server stream transport

View Source
var DefaultServerTransport = NewServerTransport(transport.WithReusePort(true))

DefaultServerTransport : Construct and encapsulate the grpc server transport instance

View Source
var DefaultStreamClient = NewStreamClient()

DefaultStreamClient Generate a new StreamClient

Functions

func NewServerStreamTransport

func NewServerStreamTransport(opt ...transport.ServerTransportOption) transport.ServerStreamTransport

NewServerStreamTransport Create grpc_stream transport

func NewServerTransport

func NewServerTransport(opt ...transport.ServerTransportOption) transport.ServerTransport

NewServerTransport create transport

func NewStreamClient

func NewStreamClient() stream.Client

NewStreamClient Generate a new StreamClient

func ParseGRPCMetadata

func ParseGRPCMetadata(ctx context.Context) map[string][]string

ParseGRPCMetadata Called by the trpc-go server to obtain the metadata of the client

func Register

func Register(serviceName string, metadata string, methodInfos []RegisterMethodsInfo) error

Register All external routes used to statically register grpc service, and the mapping of the return type

func RegisterStream

func RegisterStream(serviceName, metadata string, streamInfos []server.StreamDesc,
	svr interface{}, handlerType interface{}) error

RegisterStream Register grpc stream description information Keep the previous RegisterMethod method, which can be collected later

func StreamHandler

func StreamHandler(srv interface{}, s grpc.ServerStream) error

StreamHandler Encapsulate trpc.Handler as grpcHandler

func WithHeader

func WithHeader(ctx context.Context, header *Header) context.Context

WithHeader trpc-go client call, set the md sent to the server, or accept the md from the server

func WithServerGRPCMetadata

func WithServerGRPCMetadata(ctx context.Context, key string, value []string)

WithServerGRPCMetadata Called by the trpc-go server to send metadata

Types

type ClientCodec

type ClientCodec struct{}

ClientCodec is the codec for the grpc client, does nothing

func (*ClientCodec) Decode

func (c *ClientCodec) Decode(msg codec.Msg, buffer []byte) (rspbody []byte, err error)

Decode is a decoder for the grpc client, does nothing

func (*ClientCodec) Encode

func (c *ClientCodec) Encode(msg codec.Msg, rspbody []byte) (buffer []byte, err error)

Encode is the encoder for the grpc client and does nothing

type GrpcToTrpcLayer

type GrpcToTrpcLayer struct {
	Handler transport.Handler
}

GrpcToTrpcLayer implements GrpcToTrpcer and offers a handler of grpc server.

func (*GrpcToTrpcLayer) Handle

func (g *GrpcToTrpcLayer) Handle(srv interface{}, ctx context.Context, dec func(interface{}) error,
	_ grpc.UnaryServerInterceptor) (out interface{}, err error)

Handle req and resp are passed to trpc-go through ctx, and req is obtained from ctx and written to resp in the

generated stub without repeated serialization.

Obtaining the input and output types of the method from GrpcRegisterInfoMap is still indispensable. If this piece

of code can be placed in the stub, there is no need to record the input and output types.

type GrpcToTrpcer

type GrpcToTrpcer interface {
	Handle(srv interface{}, ctx context.Context, dec func(interface{}) error,
		interceptor grpc.UnaryServerInterceptor) (out interface{}, err error)
}

GrpcToTrpcer is an interface to represent handler of grpc server.

type Header struct {
	Req         interface{}         // request
	Rsp         interface{}         // response
	InMetadata  map[string][]string // metadata from client
	OutMetadata map[string][]string // metadata send to client
}

Header stored in context to communicate with trpc

type RegisterInfo

type RegisterInfo struct {
	Metadata    string
	ServerFunc  interface{}
	HandlerType interface{}
	MethodsInfo map[string]RegisterMethodsInfo
	StreamsInfo map[string]server.StreamDesc
}

RegisterInfo grpc Information required for registration

type RegisterMethodsInfo

type RegisterMethodsInfo struct {
	Method  server.Method
	ReqType reflect.Type
	RspType reflect.Type
}

RegisterMethodsInfo Register the content of the method

type RegisterStreamsInfo

type RegisterStreamsInfo struct {
	server.StreamDesc
}

RegisterStreamsInfo Register the content of the stream

type ServerCodec

type ServerCodec struct {
}

ServerCodec Server codec

func (*ServerCodec) Decode

func (s *ServerCodec) Decode(msg codec.Msg, reqbuf []byte) (reqbody []byte, err error)

Decode ServerCodec.Decode for decoding

func (*ServerCodec) Encode

func (s *ServerCodec) Encode(msg codec.Msg, reqbuf []byte) (reqbody []byte, err error)

Encode ServerCodec.Encode for coding

type ServerStreamTransport

type ServerStreamTransport struct {
	// contains filtered or unexported fields
}

ServerStreamTransport transport layer

func (*ServerStreamTransport) Close

func (t *ServerStreamTransport) Close(ctx context.Context)

Close When the server is abnormal, call Close to clean up the scene

func (*ServerStreamTransport) ListenAndServe

func (t *ServerStreamTransport) ListenAndServe(ctx context.Context, opt ...transport.ListenServeOption) error

ListenAndServe Start grpc monitoring

func (*ServerStreamTransport) Send

func (t *ServerStreamTransport) Send(ctx context.Context, req []byte) error

Send Execute the sending logic, where the lower layer is caught by grpcShtreamHandle, and Send is not used

type ServerTransport

type ServerTransport struct {
	// contains filtered or unexported fields
}

ServerTransport transport layer

func (*ServerTransport) ListenAndServe

func (t *ServerTransport) ListenAndServe(ctx context.Context, opt ...transport.ListenServeOption) error

ListenAndServe process configuration

type StreamClient

type StreamClient struct {
	// contains filtered or unexported fields
}

StreamClient grpc.Stream client implementation

func (*StreamClient) NewStream

func (s *StreamClient) NewStream(ctx context.Context, desc *client.ClientStreamDesc, method string,
	opt ...client.Option) (client.ClientStream, error)

NewStream Generate streamConn and store

Directories

Path Synopsis
examples
servers/impl/trpc
Package trpc 实现接口
Package trpc 实现接口

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL