grpc执行–go_out报错

执行命令:

protoc --go_out=./   ./a.proto

报错:

ERROR: 2020/10/21 11:54:10 [profiling] error parsing flags: when -address isn't specified, you must include -stream-stats-catapult-json
--go_out: protoc-gen-go: Plugin failed with status code 1.

解决:(原因:找不到protoc-gen-go可执行文件路径)

protoc --plugin=protoc-gen-go=../../bin/protoc-gen-go.exe --go_out=plugins=grpc:./ ./helloworld/helloworld.p
roto

简单实现grpc通信

仿照别人代码实现

1.新建python项目,创建文件夹

编辑helloworld.proto文件

syntax = "proto3";

package rpc_package;

// define a service
service HelloWorldService {
    // define the interface and data type
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// define the data type of request
message HelloRequest {
    string name = 1;
}

// define the data type of response
message HelloReply {
    string message = 1;
}

执行,生成rpc_package文件夹下的两个文件

python -m grpc_tools.protoc -I=./protos --python_out=./rpc_package
 --grpc_python_out=./rpc_package ./protos/helloworld.proto
2.安装模块
python -m pip install grpcio 
python -m pip install grpcio-tools
3.编辑server.py和lient.py文件

hello_server.py

#!/usr/bin/env python
# -*-coding: utf-8 -*-

from concurrent import futures
import grpc
import logging
import time

from rpc_package.helloworld_pb2_grpc import add_HelloWorldServiceServicer_to_server, \
    HelloWorldServiceServicer
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply


class Hello(HelloWorldServiceServicer):

    # 这里实现我们定义的接口
    def SayHello(self, request, context):
        return HelloReply(message='Hello, %s!' % request.name)


def serve():
    # 这里通过thread pool来并发处理server的任务
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    # 将对应的任务处理函数添加到rpc server中
    add_HelloWorldServiceServicer_to_server(Hello(), server)

    # 这里使用的非安全接口,世界gRPC支持TLS/SSL安全连接,以及各种鉴权机制
    server.add_insecure_port('[::]:50000')
    server.start()
    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == "__main__":
    logging.basicConfig()
    serve()

编辑hello_client.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import print_function
import logging

import grpc
from rpc_package.helloworld_pb2 import HelloRequest, HelloReply
from rpc_package.helloworld_pb2_grpc import HelloWorldServiceStub

def run():
    # 使用with语法保证channel自动close
    with grpc.insecure_channel('localhost:50000') as channel:
        # 客户端通过stub来实现rpc通信
        stub = HelloWorldServiceStub(channel)

        # 客户端必须使用定义好的类型,这里是HelloRequest类型
        response = stub.SayHello(HelloRequest(name='eric'))
    print ("hello client received: " + response.message)

if __name__ == "__main__":
    logging.basicConfig()
    run()
4.执行

窗口1,先执行python hello_server.py

窗口2,执行 python hello_client.py

输出  hello client received: Hello, eric!   成功