grpc python实例demo

最近换了新的项目,接触到了新的技术grpc,本着热爱&不学习就会落后的精神,自己闲来也照葫芦画瓢了搞个demo。

一、grpc概念

先看看官方的文档:
gRPC 一开始由 google 开发,是一款语言中立、平台中立、开源的远程过程调用(RPC)系统。gRPC 是一个高性能、开源和通用的 RPC 框架,面向移动和 HTTP/2 设计。目前提供 C、Java 和 Go 语言版本,分别是:grpc, grpc-java,grpc-go. 其中 C 版本支持 C, C++, Node.js,Python, Ruby, Objective-C, PHP和 C# 支持.

gRPC 基于 HTTP/2 标准设计,带来诸如双向流、流控、头部压缩、单 TCP 连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。

二、grpc环境准备

1、本次demo使用python版本,首先需要准备python3环境:

Python 3.5或更高版本

pip 版本9.0.1或更高

2、安装grpc

pip install grpcio

3、安装 ProtoBuf 相关的 python 依赖库

pip install protobuf

4、安装 python grpc 的 protobuf 编译工具:

pip install grpcio-tools

三、开始demo项目

1、创建一个空的项目

2、项目下新建一个proto文件夹

3、新建helloworld.proto文件,内容如下:

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

4、执行命令
切换到上一步的目录,执行
python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. helloworld.proto
5、创建服务端和客户端代码

#coding=utf-8
from concurrent import futures
import time
import grpc
from proto import helloworld_pb2
from proto import helloworld_pb2_grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeter(helloworld_pb2_grpc.GreeterServicer):
    # 工作函数
    def SayHello(self, request, context):
        print(request.name)
        message = "This message is from Server.And what i want to say is hello \" " + request.name + " \"";
        return helloworld_pb2.HelloReply(message = message)


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

if __name__ == '__main__':
    serve()
#coding=utf-8
from __future__ import print_function

import grpc

from proto import helloworld_pb2
from proto import helloworld_pb2_grpc


def run():
    channel = grpc.insecure_channel('localhost:50051')
    stub = helloworld_pb2_grpc.GreeterStub(channel)
    response = stub.SayHello(helloworld_pb2.HelloRequest(name='Hello World! This is message from client!'))
    print("Greeter client received: " + response.message)


if __name__ == '__main__':
    run()

6、运行起来测试


image.png

成功了!

你可能感兴趣的:(grpc python实例demo)