gRPC Quick startをやってみる
はじめに
以下のチュートリアルに従い、gRPCのサンプルを実行してみる。
事前に以下を読むべし。
環境
実施
gRPCインストール
(venv) satoukensuke@MacBook-Pro Desktop % python -m pip install grpcio Requirement already satisfied: grpcio in ./venv/lib/python3.9/site-packages (1.39.0) Requirement already satisfied: six>=1.5.2 in ./venv/lib/python3.9/site-packages (from grpcio) (1.16.0)
gRPCツールインストール
gRPCツールには、protcol bufferコンパイラprotoc
と .proto
からサーバ、クライアントコードを生成する機能が含まれている。
(venv) satoukensuke@MacBook-Pro Desktop % python -m pip install grpcio-tools Requirement already satisfied: grpcio-tools in ./venv/lib/python3.9/site-packages (1.39.0) Requirement already satisfied: setuptools in ./venv/lib/python3.9/site-packages (from grpcio-tools) (57.4.0) Requirement already satisfied: grpcio>=1.39.0 in ./venv/lib/python3.9/site-packages (from grpcio-tools) (1.39.0) Requirement already satisfied: protobuf<4.0dev,>=3.5.0.post1 in ./venv/lib/python3.9/site-packages (from grpcio-tools) (3.17.3) Requirement already satisfied: six>=1.5.2 in ./venv/lib/python3.9/site-packages (from grpcio>=1.39.0->grpcio-tools) (1.16.0)
サンプルダウンロード
Githubリポジトリからcloneして、サンプルディレクトリに移動。
(venv) satoukensuke@MacBook-Pro Desktop % git clone -b v1.38.0 https://github.com/grpc/grpc Cloning into 'grpc'... 略... Updating files: 100% (9108/9108), done. (venv) satoukensuke@MacBook-Pro Desktop % cd grpc/examples/python/helloworld
サンプルの起動
gRPCのリクエストを受け取り、返却するサーバを起動する。
(venv) satoukensuke@MacBook-Pro helloworld % python greeter_server.py
別ターミナルを開き、grpc/examples/python/helloworld
に移動、gRPCリクエストをサーバに投げるクライアントを実行する。
(venv) satoukensuke@MacBook-Pro Desktop % cd grpc/examples/python/helloworld (venv) satoukensuke@MacBook-Pro helloworld % python greeter_client.py Greeter client received: Hello, you!
メモ
greeter_client.py
では、name
パラメタに値you
をポート50051
に投げている。
def run(): # NOTE(gRPC Python Team): .close() is possible on a channel and should be # used in circumstances in which the with statement does not fit the needs # of the code. with grpc.insecure_channel('localhost:50051') as channel: stub = helloworld_pb2_grpc.GreeterStub(channel) response = stub.SayHello(helloworld_pb2.HelloRequest(name='you')) print("Greeter client received: " + response.message)
greeter_server.py
では、リクエストname
パラメタの値から文字列を生成している。
サンプルではHello, you!
が生成される。
生成文字列は、最終的にレスポンスmessage
として返却している。
class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
図にするとこう。