python example of gRPC

Reference URL:

https://segmentfault.com/a/1190000015220713?utm_source=channel-hottest

gRPC is a high performance, open source framework and a common RPC, for mobile and HTTP / 2 design. Currently provides C, Java, and Go language versions, namely:. Grpc, grpc-java, grpc-go where C version supports C, C ++, Node.js, Python , Ruby, Objective-C, PHP and C # support.

gRPC HTTP / 2 based on standard design, such as a bi-directional flow brings, flow control, header compression, multiplexing multiple single TCP connection requests on other bits. These characteristics make it a better performance on a mobile device, more power and space occupancy.

One,hello.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;
}

 

Two, rRPC tools compile command

python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. ./hello.proto

Generates two files:

  • hello_pb2.py This file contains the request (generated HelloRequest) and Response ( HelloReply) class.
  • hello_pb2_grpc.py This file contains the generated client ( GreeterStub) and server ( GreeterServicer) class.

Although it is already generating a server and client code, but we also need to implement a manual as well as the method call.

Three, greeter_server.py file contents

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 (the Greeter (), Server) 
    server.add_insecure_port ( ' [::]: 50051 ' ) 
    server.start ()   # Start () does not block, if you run your code when no other things to do, you You may need to wait for the cycle. 
    the try :
         the while True: 
            the time.sleep (_ONE_DAY_IN_SECONDS) 
    the except the KeyboardInterrupt: 
        server.stop (0) 

IF  the __name__ == ' __main__ ' : 
    serve ()

 

Four, greeter_client.py file contents

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()

 

Fifth, the operating results

Guess you like

Origin www.cnblogs.com/aguncn/p/11520331.html