LoginSignup
2
2

More than 3 years have passed since last update.

Go + Python + gRPC 技術調査

Last updated at Posted at 2019-07-22

Install


go get -u github.com/golang/protobuf/protoc-gen-go
go get -u google.golang.org/grpc

ProtocolBufferの定義

/protosなどをディレクトリを作ってそこに格納するのが正解?


service {
  rpc GetFeature(Point) returns (Point) {}
  // rpc GetFeature(stream Point) returns (Feature) {} streamでやり取りする場合にはstreamをつける。
}

message Point {
  int32 latitude = 1; // 数字は単に識別のためのもので特に意味はない。
  int32 longitude = 2;
}

GolangでのgRPCコード生成


protoc -I routeguide/ --go_out=plugins=grpc:routeguide routeguide/route_guide.proto 
  • -I ./routeguide protoファイルが存在するディレクトリ?
  • --go_out=plugins=grpc:routeguide 出力ディレクトリ
  • routeguide/route_guide.proto 対象protoファイル

pythonでのgRPCコード生成


pip install grpcio-tools
python -m grpc_tools.protoc -I./routeguide --python_out=./routeguide --grpc_python_out=./routeguide ./routeguide/route_guide.proto
  • -m grpc_tools.protoc commandの指定?
  • -I ./routeguide protoファイルが存在するディレクトリ?
  • --python_out=./routeguide pythonの出力ディレクトリ1
  • --grpc_python_out=./routeguide pythonの出力ディレクトリ2
  • ./routeguide/route_guide.proto 対象protoファイル

GolangでのClient


import (
  "google.golang.org/grpc"
  pb "google.golang.org/grpc/examples/route_guide/routeguide"
)

func printFeature(client pb.RouteGuideClient, point *pb.Point) {
  log.Printf("Getting feature for point (%d, %d)", point.Latitude, point.Longitude)
  ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  defer cancel()
  feature, err := client.GetFeature(ctx, point)
  if err != nil {
    log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err)
  }
  log.Println(feature)
}

func main {
  var opts []grpc.DialOption
  opts = append(opts, grpc.WithInsecure()) // Connection uses plain TCP, TLS also exists

  serverAddr := "127.0.0.1:10000"
  conn, err := grpc.Dial(*serverAddr, opts...)

  if err != nil {
    log.Fatalf("fail to dial: %v", err)
  }
  defer conn.Close()

  client := pb.NewRouteGuideClient(conn)
  printFeature(client, &pb.Point{Latitude: 409146138, Longitude: -746188906})
}

PythonでのServer


import grpc

import route_guide_pb2
import route_guide_pb2_grpc
import route_guide_resources


class RouteGuideServicer():
    """Provides methods that implement functionality of route guide server."""

    def GetFeature(self, request, context):
        return route_guide_pb2.Feature(name="", location=request)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    route_guide_pb2_grpc.add_RouteGuideServicer_to_server(
        RouteGuideServicer(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    # server.stop(0)

if __name__ == '__main__':
    logging.basicConfig()
    serve()

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2