rainit2006 / My_AWS-Cloud

0 stars 0 forks source link

GRPC #21

Open rainit2006 opened 5 years ago

rainit2006 commented 5 years ago

gRPCとは Googleによって開発されたRPCフレームワークです。

gRPCの特徴の一つとしてデータのシリアライズに「Protocol buffers」という技術が使われています。 これはメッセージデータの構造、手続きの構造を定義するためのインタフェース記述言語(IDL: Interface Description Language)に属するもので「.proto」という拡張子のファイルにメッセージタイプを定義します。

.protoサンプル

message Person {
  // 基本は[型名] [名前] でデータを定義するみたいです
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  // enumで固定の数値も定義できる
  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

gRPCではこの「.proto」ファイルを各言語のコンパイラ(protocol buffer compiler)でコンパイルすることで、インターフェース処理コードを自動生成します。

■gRPCを使う時の流れ  https://grpc.io/docs/quickstart/python.html 1、ツールのインストール gRPCの実装には次のツールが必要なのでインストールします gRPCライブラリ(grpc) Protorcol Buffers V3コンパイラ(protoc) protocol bufferのGoプラグイン(protoc-gen-go) 2、「.protoファイル」にインターフェースを定義する

/ 文件名 hello.proto
syntax = "proto3";

package hello;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

3、定義ファイルをコンパイル $ python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto 它会生成下面两个文件:
helloworld_pb2.py : contains our generated request and response classes。 helloworld_pb2_grpc.py : contains our generated client and server classes.

4、创建服务端代码 创建和运行 Greeter 服务可以分为两个部分: 实现我们服务定义的生成的服务接口:做我们的服务的实际的“工作”的函数。 运行一个 gRPC 服务器,监听来自客户端的请求并传输服务的响应。

在当前目录,打开文件 greeter_server.py,实现一个新的函数:

from concurrent import futures
import time
import grpc
import hello_pb2
import hello_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Greeter(hello_pb2_grpc.GreeterServicer):
    # 工作函数
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(message='Hello, %s!' % request.name)

def serve():
    # gRPC 服务器
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()  # start() 不会阻塞,如果运行时你的代码没有其它的事情可做,你可能需要循环等待。
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

更新客户端代码: 在当前目录,打开文件 greeter_client.py,实现一个新的函数:

from __future__ import print_function
import grpc
import hello_pb2
import hello_pb2_grpc

def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = hello_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(hello_pb2.HelloRequest(name='goodspeed'))
    print("Greeter client received: " + response.message)

if __name__ == '__main__':
    run()

运行代码 : 1,首先运行服务端代码 python greeter_server.py 2, 然后运行客户端代码 python greeter_client.py 3,# output Greeter client received: Hello, goodspeed!

rainit2006 commented 5 years ago

gRPCはHTTP/2を前提として定義された規格されています。※ HTTP/2については詳細は割愛します。 HTTP/2を前提としているためクライアントとサーバーの双方向通信において柔軟なやりとりが可能というのもメリットの一つのようです。

rainit2006 commented 5 years ago

image