Python使用GRPC

0.安装依赖库

pip install grpcio
pip install protobuf
pip install grpcio-tools

  

1.编写proto文件

// Copyright 2015 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// 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;
}

  

2.编译生成proto对应源文件

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. helloworld.proto

  

3.编写server端代码

# -*- coding: utf-8 -*-
# Author: areful
#
# pip install grpcio
# pip install protobuf
# pip install grpcio-tools
# ...

# Copyright 2015, Google Inc.
# All rights reserved.

"""The Python implementation of the GRPC helloworld.Greeter server."""

import time
from concurrent import futures

from gj.grpc.helloworld.helloworld_pb2 import *
from gj.grpc.helloworld.helloworld_pb2_grpc import *

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeter(GreeterServicer):

    def SayHello(self, request, context):
        return HelloReply(message='Hello, %s!' % request.name)


def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == '__main__':
    serve()

  

4.编写client端代码

# -*- coding: utf-8 -*-
# Author: areful
#
# pip install grpcio
# pip install protobuf
# pip install grpcio-tools
# ...

# Copyright 2015, Google Inc.
# All rights reserved.

"""The Python implementation of the GRPC helloworld.Greeter client."""

from __future__ import print_function

from gj.grpc.helloworld.helloworld_pb2 import *
from gj.grpc.helloworld.helloworld_pb2_grpc import *


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


if __name__ == '__main__':
    run()

  5.分别运行server、client代码,运行输出如下:

 

posted on 2019-02-14 06:11  areful  阅读(4753)  评论(0编辑  收藏  举报

导航