gRPC HelloWorldのテスト

I.概要

What's gRPC?
gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.(gRPC是可以在任何环境中运行的现代的开源高性能RPC框架。它可以通过可插拔的支持来有效地连接数据中心内和跨数据中心的服务,以实现负载平衡,跟踪,运行状况检查和身份验证。它也适用于分布式计算的最后一英里,以将设备,移动应用程序和浏览器连接到后端服务。)
我们可以用一句话来概括:A high-performance, open-source universal RPC framework
RPC(remote procedure call 远程过程调用)框架实际是提供了一套机制,使得应用程序之间可以进行通信,而且也遵从server/client模型。使用的时候客户端调用server端提供的接口就像是调用本地的函数一样。

その
ような状況はgRPCそれを使用するために必要なものの下で?
状況は、我々はより厳しい制約のためのインタフェースを持つようにしたい、私たちは社外にも人にもこのサービスにアクセスすることができ、公共サービス、多くの人々を、提供など、インターフェイス上の厳しい制約を必要とし、我々はにクライアントをしたくありません我々は、多くの場合、より厳しい制約をインタフェースする必要がある、特に安全係数を考慮して、任意のデータを渡します。その後gRPCはいるProtobufによる厳格なインタフェースの制約を提供することができます。
高い性能要件に関して。時々 、私たちのサービスは、大量のデータを渡す必要がありますが、私たちのパフォーマンスに影響を与えたくないいるProtobufによって、我々はバイナリ形式にエンコードされたデータは、データ転送の通常はるかに小さい量を圧縮することができますので、この時間も、gRPCサービスと見なすことができますそして、HTTP2によって、私たちは、このように大幅に通信効率を向上させること、非同期要求を達成することができます。
しかし、我々は通常、一人でgRPCを行っていないが、使用するためのコンポーネントとしてgRPC、本番環境の場合には、我々は分散処理システムを使用するために大規模な同時必要性に直面しているので、行ったり来たり、しかしgRPCなかっただろう分散システムの必要な構成要素のいくつかを提供します。また、実際の必要性はそれほどの負荷バランシング、電流制限ヒューズ、モニタリング報告書に必要なコンポーネントジン、サービス登録と発見、およびなどのオンラインサービスを、提供します。

第二に、テスト

ハローワールドGRPCテストの次の開始
GRPCは、典型的には、以下のステップを含む使用:
1、およびインタフェースデータ型いるProtobuf定義するために
、2 gRPCサーバ側コード調製
3、gRPCクライアント側コードを調製

図1に示すように、インタフェースおよびデータ型いるProtobufによって定義されます

私は本当にマックがあるため、彼はのpython3をインストールしていることが必要で、Macはpython2を来て、Pythonで使用しました。
まずPIP3インストールgrpcといるProtobuf

(lxc) liuxuchong:untitled liuxuchong$  pip3 install grpcio
Collecting grpcio
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/0d/27/0413a5dffd7ddca4ea43cffd22f46ec2b26a5ed18c974e4448763e758a9b/grpcio-1.25.0-cp37-cp37m-macosx_10_9_x86_64.whl
  Downloading https://files.pythonhosted.org/packages/0d/27/0413a5dffd7ddca4ea43cffd22f46ec2b26a5ed18c974e4448763e758a9b/grpcio-1.25.0-cp37-cp37m-macosx_10_9_x86_64.whl (2.3MB)
    100% |████████████████████████████████| 2.3MB 8.1kB/s 
Collecting six>=1.5.2 (from grpcio)
  Using cached https://files.pythonhosted.org/packages/65/26/32b8464df2a97e6dd1b656ed26b2c194606c16fe163c695a992b36c11cdf/six-1.13.0-py2.py3-none-any.whl
Installing collected packages: six, grpcio
Successfully installed grpcio-1.25.0 six-1.13.0

(lxc) liuxuchong:untitled liuxuchong$  pip3 install protobuf
Collecting protobuf
  Downloading https://files.pythonhosted.org/packages/a5/c6/a8b6a74ab1e165f0aaa673a46f5c895af8780976880c98934ae82060356d/protobuf-3.10.0-cp37-cp37m-macosx_10_9_intel.whl (1.4MB)
    100% |████████████████████████████████| 1.4MB 83kB/s 
Requirement already satisfied: setuptools in ./venv/lxc/lib/python3.7/site-packages/setuptools-40.8.0-py3.7.egg (from protobuf) (40.8.0)
Requirement already satisfied: six>=1.9 in ./venv/lxc/lib/python3.7/site-packages (from protobuf) (1.13.0)
Installing collected packages: protobuf
Successfully installed protobuf-3.10.0

定義されているProtobuf

それはgrpcサービス宣言されているシンプルいるProtobufファイル、次の定義。
以下、grpchello.protoを作成するには、プロトディレクトリとファイルを作成します。

syntax = "proto3";
package grpcDemo;

message HelloRequest {
   string name = 1;
}

message HelloReply {
   string message = 1;
}

service gRPC {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

コンパイルいるProtobuf

いるProtobufは、私たちのために、フレームの手パイソンバージョンのメッセージの定義やサービスを生成するコンパイラを使用します。

python -m grpc-tools.protoc -I./proto --python_out =。--grpc_python_out =。grpchello.proto
/ユーザ/ liuxuchong / PycharmProjects /無題/ venv / LXC / binに/ pythonの:エラー'grpc-tools.protoc'のモジュールの仕様を見つけながら(ModuleNotFoundError: 'grpc-ツール'という名前のないモジュール)

私たちは、grpc-ツールを持っていないヒント、ピップでそれをインストール

python3 -mピップ--user grpcio-ツールをインストール

そして、上記のコマンドを実行します。

2つのファイルを生成し、現在のディレクトリでは:

  • grpchello_pb2.py
  • grpchello_pb2_grpc.py

最初のファイル、メッセージ定義ファイルを表示します。

# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: grpchello.proto

import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='grpchello.proto',
  package='grpcDemo',
  syntax='proto3',
  serialized_options=None,
  serialized_pb=_b('\n\x0fgrpchello.proto\x12\x08grpcDemo\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2B\n\x04gRPC\x12:\n\x08SayHello\x12\x16.grpcDemo.HelloRequest\x1a\x14.grpcDemo.HelloReply\"\x00\x62\x06proto3')
)

_HELLOREQUEST = _descriptor.Descriptor(
  name='HelloRequest',
  full_name='grpcDemo.HelloRequest',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='name', full_name='grpcDemo.HelloRequest.name', index=0,
      number=1, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      serialized_options=None, file=DESCRIPTOR),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  serialized_options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=29,
  serialized_end=57,
)

そして、grpcサービス定義を見て:

from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='grpchello.proto',
  package='grpcDemo',
  syntax='proto3',
  serialized_options=None,
  serialized_pb=_b('\n\x0fgrpchello.proto\x12\x08grpcDemo\"\x1c\n\x0cHelloRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x01 \x01(\t2B\n\x04gRPC\x12:\n\x08SayHello\x12\x16.grpcDemo.HelloRequest\x1a\x14.grpcDemo.HelloReply\"\x00\x62\x06proto3')
)

_HELLOREQUEST = _descriptor.Descriptor(
  name='HelloRequest',
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='grpchello.proto',
  package='grpcDemo',
  syntax='proto3',
  serialized_options=None,
  serialized_pb=_b('\n\x0fgrpchello.proto\x12\x08grpcDemo\"\x1c\n\x0cHelloRequest\\
x12\x0c\n\x04name\x18\x01 \x01(\t\"\x1d\n\nHelloReply\x12\x0f\n\x07message\x18\x011
 \x01(\t2B\n\x04gRPC\x12:\n\x08SayHello\x12\x16.grpcDemo.HelloRequest\x1a\x14.grpcc
Demo.HelloReply\"\x00\x62\x06proto3')
)

_HELLOREQUEST = _descriptor.Descriptor(
  name='HelloRequest',
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc

import grpchello_pb2 as grpchello__pb2

class gRPCStub(object):
  # missing associated documentation comment in .proto file
  pass

  def __init__(self, channel):
    """Constructor.

    Args:
      channel: A grpc.Channel.
    """
    self.SayHello = channel.unary_unary(
        '/grpcDemo.gRPC/SayHello',
        request_serializer=grpchello__pb2.HelloRequest.SerializeToString,
        response_deserializer=grpchello__pb2.HelloReply.FromString,
        )

class gRPCServicer(object):
  # missing associated documentation comment in .proto file
  pass

  def SayHello(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!')

def add_gRPCServicer_to_server(servicer, server):
  rpc_method_handlers = {
      'SayHello': grpc.unary_unary_rpc_method_handler(
          servicer.SayHello,
          request_deserializer=grpchello__pb2.HelloRequest.FromString,
          response_serializer=grpchello__pb2.HelloReply.SerializeToString,
      ),
  }
  generic_handler = grpc.method_handlers_generic_handler(
      'grpcDemo.gRPC', rpc_method_handlers)
  server.add_generic_rpc_handlers((generic_handler,))
  • grpcサービス定義フレーム手足では、コールgrpcサービスを使用して、クライアントに割り当てられているgRPCStubを、定義されました。
  • 定義されたサービスクラスgRPCServicer、sayHelloメソッドは、我々は、サブクラスで実装する必要があります。クラスとそれを登録するgrpc API呼び出しの実現のために定義されadd_gRPCServicer_to_server方法。

本明細書で使用されるいくつかの主な方法(複数可):

  • grpc.server - RPCがサービスすることが可能なサーバーを作成します。
  • grpc.method_handlers_generic_handler - RpcMethodHandlersからGenericRpcHandlerを作成します。
  • grpc.unary_unary_rpc_method_handler - 単項 - 単項RPCメソッドのRpcMethodHandlerを作成します。

サービスを実装します

私たちのクラスで実装サービスは、サービスメソッドを使用していること、およびネットワークに公開します。

# -*- coding: utf-8 -*-
import grpc
import time
from concurrent import futures 
import grpchello_pb2, grpchello_pb2_grpc

_HOST = 'localhost'
_PORT = '8188'

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class gRPCServicerImpl(grpchello_pb2_grpc.gRPCServicer):

    def SayHello(self, request, context):
        print ("called with " + request.name)
        return grpchello_pb2.HelloReply(message='Hello, %s!' % request.name)

def serve():
  server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
  grpchello_pb2_grpc.add_gRPCServicer_to_server(gRPCServicerImpl(), server)
  server.add_insecure_port('[::]:'+_PORT)
  server.start()
  try:
    while True:
      time.sleep(_ONE_DAY_IN_SECONDS)
  except KeyboardInterrupt:
    server.stop(0)

if __name__ == '__main__':
    serve()

これは、二つの実装が含まれています。

  • APIのgrpc(サービス実装クラス)gRPCServicerImpl、実現sayHelloメソッドの実装で1、。
  • 2は、その後、ネットワークサービスに対処するためのAPIをgrpc登録するには、ネットワークサービスとポートを定義します。ここでgrpc.serverクラスの簡単な使用。

クライアントのクライアントを使用してください

クライアントでは、grpcサービスAPIを呼び出します。

# -*- coding: utf-8 -*-
"""The Python implementation of the gRPC client."""
from __future__ import print_function
import grpc
from grpchello_pb2  import *    ## or import grpchello_pb2
from grpchello_pb2_grpc import *
## No grpcDemo!  from grpcDemo import grpchello_pb2, grpchello_pb2_grpc #error!

_PORT = '8188'

def run():
    conn = grpc.insecure_channel(_HOST + ':' + _PORT)
    client = gRPCStub(channel=conn)
    response = client.SayHello(HelloRequest(name='lxc'))
    print("received: " + response.message)

## 
if __name__ == '__main__':

    if len(sys.argv)== 2:
        print (sys.argv[1])
        _HOST = sys.argv[1]
    else:
        _HOST = 'localhost'

    #    
    run()

説明:

  • 1、DEF insecure_channel(ターゲット、オプション=なし):
    -サーバーへの安全でないチャンネルを作成します。
  • 2は、クライアントはスタブ、APIを呼び出すサービスを使用しています。

テスト

それぞれ、サービスを起動し、クライアントを起動するには、呼び出しの結果を見ることができます。
また、Javaの起動grpcサービスのC#バージョン、クライアント、成功を呼び出すことができます。

そして、実行

(lxc) liuxuchong:untitled liuxuchong$  python3 grpchello_pb2.py
Traceback (most recent call last):
  File "grpchello_pb2.py", line 7, in <module>
    from google.protobuf import descriptor as _descriptor
ModuleNotFoundError: No module named 'google'

何のGoogleのテンプレートがヒント
オンラインソリューションを確認していない、次のようです

GoogleのPIP3インストール
PIP3がいるProtobufをインストール

その後、別のPYファイルを実行します

python3 grpchello_pb2_grpc.py
Traceback (most recent call last):
  File "grpchello_pb2_grpc.py", line 2, in <module>
    import grpc

ストレンジは、ちょうど明らかにも何のテンプレートが存在しないことを示唆している、インストール、およびAをインストール

pip3 install grpcio
Collecting grpcio
  Using cached https://files.pythonhosted.org/packages/0d/27/0413a5dffd7ddca4ea43cffd22f46ec2b26a5ed18c974e4448763e758a9b/grpcio-1.25.0-cp37-cp37m-macosx_10_9_x86_64.whl
Requirement already satisfied: six>=1.5.2 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from grpcio) (1.13.0)
Installing collected packages: grpcio
Successfully installed grpcio-1.25.0

案の定、ちょうど失われたインストールされています。
そして、実行のpython3のget_service.py

gRPC HelloWorldのテスト
実行するために新しいウィンドウを開いて
のpython3 client.pyを
gRPC HelloWorldのテスト

元のウィンドウでは、LXCと呼ばれる見ることができます
gRPC HelloWorldのテスト

参考:
HTTPS://www.jianshu.co×××c947d98e192
https://blog.csdn.net/whereismatrix/article/details/78595550

おすすめ

転載: blog.51cto.com/13670314/2450179