zoukankan      html  css  js  c++  java
  • rpc学习

    步骤一.环境准备:

          安装gRPC  :  pip install grpcio

          安装 ProtoBuf 相关的 python 依赖库:  pip install protobuf

          安装 python grpc 的 protobuf 编译工具: pip install grpcio-tools

    步骤二.开始定义并编译proto文件:

    创建文件夹 my_proto, 在里面写一个helloworld.proto文件

    -------------------------helloworld.proto :------------------------------------

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

     

    然后编译这个文件: python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. helloworld.proto

    会生成2个文件: 

            helloworld_pb2.py   (包含request(HelloRequest) 和 response(HelloReply) 类)

            helloworld_pb2_grpc.py   (包含生成的 客户端(GreeterStub)和服务端(GreeterServicer)的类。)

    步骤三.开始写 client 和 server 代码

    ----------------------------client.py 开始---------------------------------------------------------------

    from __future__ import print_function

    import grpc

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

    ----------------------------server.py 开始---------------------------------------------------------------

    # -*- coding=utf-8 -*-

    from concurrent import futures
    import time
    import grpc
    import helloworld_pb2
    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()

    我们最后的文件结构是这样:

           my_proto  : helloworld.proto 、helloworld_pb2_grpc.py、 helloworld_pb2.py  、client.py 、server.py

    最后:看看运行效果:

    >python server.py 
    sever is opening ,waiting for message...
    Hello World! This is message from client!
    Hello World! This is message from client!
    Hello World! This is message from client!

    >python client.py
    Greeter client received: This message is from Server.And what i want to say is hello " Hello World! This is message from client! "

  • 相关阅读:
    C++_构造函数与析构函数
    华为模拟机试_C++题解
    OOP_由C到C++
    OOP_面向对象程序设计概述
    java ssm 后台框架平台 项目源码 websocket即时聊天发图片文字 好友群组 SSM源码
    springmvc SSM 多数据源 shiro redis 后台框架 整合
    【面经】5年Java面试亲身经验
    【快手初面】要求3个线程按顺序循环执行,如循环打印A,B,C
    手工实现HttpBasic校验
    Java 并发系列(一) ThreadPoolExecutor源码解析及理解
  • 原文地址:https://www.cnblogs.com/yuzhaoblog/p/10881246.html
Copyright © 2011-2022 走看看