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 是一个高性能、通用的开源RPC框架,基于HTTP/2协议标准和Protobuf序列化协议开发,支持众多的...
    小波同学阅读 19,695评论 6 19
  • C++ 开源库列表https://en.cppreference.com/w/cpp/links/libs[htt...
    老陕西阅读 6,785评论 0 0
  • gRPC的官方Demo 按照APK 方式随意 目录:examples/android/helloworld ./g...
    简简单单敲代码阅读 9,545评论 0 2
  • 久违的晴天,家长会。 家长大会开好到教室时,离放学已经没多少时间了。班主任说已经安排了三个家长分享经验。 放学铃声...
    飘雪儿5阅读 12,193评论 16 22
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 13,587评论 0 11