Twirp対gRPC。 それは価値がありますか?

マイクロサービスアーキテクチャを使用する場合、サービス間の通信のオーバーヘッドがしばしば重大な問題になることを知っている可能性が高く、この問題に遭遇した場合、 Protobuf上のRPCフレームワークのいずれか 、たとえばGoogleのgRPC Peter BourgonによるGo-Kitなど。 それが何であるか、それをどのように使用するかを説明することは意味がありません。すべてが私の前に非常によく説明されています。 私自身、プロジェクトでgRPCを積極的に使用していますが、ここでTwichはprotobuf Twirpの実装をリリースすることにしました 。 なぜそれが必要なのか、それがどのように異なるのか疑問に思っているなら、猫の下に行ってください。



まず、TwichがProtoBufの独自バージョンをリリースした理由を見てみましょう。





ご覧のとおり、TwichがProtobufの実装を記述することにした主な理由は、単純さです。



次に、このライブラリの使用方法を見てみましょう。



Goで開発環境を既に設定している場合は、次のパッケージをインストールする必要があります



go get github.com/twitchtv/twirp/protoc-gen-twirp go get github.com/golang/protobuf/protoc-gen-go
      
      





たとえば、パラメーターとして渡された値をインクリメントする単純なサービスを作成します。



 syntax = "proto3"; service Service { rpc Increment(Request) returns (Response); } message Request { int32 valueToIncrement = 1; // must be > 0 } message Response { int32 IncrementedValue = 1; // must be > 0 }
      
      





次のコマンドを実行して、クライアントのコードを生成します



 protoc --proto_path=$GOPATH/src:. --twirp_out=. --go_out=. ./paperclips.proto
      
      





その結果、2つのファイルが作成されます。





次に、サービスの実装を追加します



 package main import ( "fmt" "log" "net/http" "context" pb "TwirpSample/Server/Twirp" ) // Server implements the Increment service type Server struct { value int32 } // NewServer creates an instance of our server func NewServer() *Server { return &Server{ value: 1, } } // Increment returns the incremented value of request.ValueToIncrement func (s *Server) Increment(ctx context.Context, request *pb.Request) (*pb.Response, error) { return &pb.Response{ IncrementedValue: request.ValueToIncrement + 1, }, nil } func main() { fmt.Printf("Starting Increment Service on :6666") server := NewServer() twirpHandler := pb.NewServiceServer(server, nil) log.Fatal(http.ListenAndServe(":6666", twirpHandler)) }
      
      





これで、 go run main.goコマンドを使用してクライアントを起動すると、HTTP経由でサービスにアクセスできます。



 curl --request "POST" \ --location "http://localhost:6666/Service/Increment" \ --header "Content-Type:application/json" \ --data '{ValueToIncrement: 0}' \ --verbose Output: {"IncrementedValue":1}
      
      





またはバイナリ形式で



 package main import ( "fmt" rpc "TwirpSample/Server/Twirp" "net/http" "context" ) func main() { fmt.Println("Twirp Client Example.") client := rpc.NewServiceProtobufClient("http://localhost:6666", &http.Client{}) v, err := client.Increment(context.Background(), &rpc.Request{ValueToIncrement: 11}) if err != nil { fmt.Println(err.Error()) } fmt.Printf("Value: %d", v.IncrementedValue) } Output: Twirp Client Example. Value: 11
      
      





一般に、フレームワーク自体のアプローチはgRPCとほとんど同じですが、実装が簡単で、同時にHTTP 1.1をサポートしています。 私の意見では、その適用性は、HTTPを介してUIと、Protobufを介してサービス間で同時に対話することを計画しているRPCサービスが必要な場合です。



参照:






All Articles