今天在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端。