fedora27 上使用grpc详解

今天在fedora上安装并测试grpc,记录以备日后查阅。

1、安装grpc

      过程很曲折,遇到的问题很多简单记录下:

    pip install --upgrade pip
    pip install grpcio
    pip install protobuf
    pip install grpcio-tools

   yum -y install  protobuf-compiler protobuf-static protobuff protobuf-devel

   dnf install protobuf-compiler.x86_64

   pip install googleapis-common-protos

2、编写proto文件

syntax = "proto3";
package example;


service FormatData {
  rpc DoFormat(Data) returns (Data){}
}
message Data {
  string text = 1;
}

3、编译proto

python -m grpc_tools.protoc --proto_path=. --python_out=. --grpc_python_out=. xxx.proto

有可能会遇到字符转换错误,如下方式解决:

vi /usr/lib64/python2.7/site-packages/grpc_tools/protoc.py 加入

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

4、编写server 端:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import time
from concurrent import futures
import test_pb2, test_pb2_grpc
 
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
_HOST = 'localhost'
_PORT = '4321'
 
class FormatData(test_pb2_grpc.FormatDataServicer):
    def DoFormat(self, Data, context):
        str = Data.text
        return test_pb2.Data(text=str.upper())
 
def serve():
    grpcServer = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
    test_pb2_grpc.add_FormatDataServicer_to_server(FormatData(), grpcServer)
    print "111111111111111111111111......."
    grpcServer.add_insecure_port('[::]:50051')
    print "222222222222222222222......."
    grpcServer.start()
    print "begin......."
    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        grpcServer.stop(0)
 
if __name__ == '__main__':
    serve()

5、编写client 端:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import grpc
import test_pb2, test_pb2_grpc
 
_HOST = 'localhost'
_PORT = '4321'
 
def run():
    print "000000000000000000000000......."
    #conn = grpc.insecure_channel('localhost', 50051)
    #print "111111111111111111111111......."
    #client = test_pb2_grpc.FormatDataStub(channel=conn)
    #print "22222222222222222222222......."
    #response = client.DoFormat(test_pb2.Data(text='hello,world!'))
    #print("received: " + response.text)
 
    with grpc.insecure_channel('localhost:50051') as channel:
        print "111111111111111111111111......."
        stub = test_pb2_grpc.FormatDataStub(channel)
        print "222222222222222222222222......."
        response = stub.DoFormat(test_pb2.Data(text='you'))
    print("Greeter client received: " + response.text)

if __name__ == '__main__':
    run()

6、先将server端执行,然后在执行client端。

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值