基于前两篇,本篇介绍下如果用Java和Python通过gRPC互相调用

安装依赖

1
2
3
pip install grpcio
pip install grpcbuf
pip install grpcio-tools

准备.proto文件

注意,该文件需要与Java项目中的.proto保持一致

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
syntax = "proto3";
package example;

// 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代码

1
python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. example/helloworld.proto

编写Python Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# from __future__ import print_function
import grpc
from example import helloworld_pb2, helloworld_pb2_grpc


def run():
# NOTE(gRPC Python Team): .close() is possible on a channel and should be
# used in circumstances in which the with statement does not fit the needs
# of the code.
with grpc.insecure_channel('10.10.10.10:50051') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
print("Greeter client received: " + response.message)


if __name__ == '__main__':
run()

grpc.insecure_channel(‘localhost:50051’) 有可能会提示failed to connect to all addresses错误,我将其修改为网卡绑定的局域网地址便可成功访问Java服务。

编写Python Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import sys
import grpc
from concurrent import futures

from example import helloworld_pb2, helloworld_pb2_grpc
from example import helloworld_pb2 as helloworld__pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24


class Greeter(helloworld_pb2_grpc.GreeterServicer):

def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)


def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)


if __name__ == '__main__':

serve()

这样,就可以实现Python Client 调用 Java gRPC server , Java Client 调用 Python gRPC server。

1
2
/home/charles/miniconda3/bin/conda run -n py_grpc --no-capture-output python /mnt/d/PycharmProjects/pygrpc/client/greeter_client.py 
Greeter client received: Hello you