念念不忘
必会回响

Java和Python通过gRPC互相调用

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

1. 安装依赖

pip install grpcio
pip install grpcbuf
pip install grpcio-tools

2. 准备.proto文件

注意,该文件需要与Java项目中的.proto保持一致
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;
}

3. 生成Python代码

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

4. 编写Python Client

#! /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服务。

5. 编写Python Server

#! /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。

/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
赞(11) 打赏
未经允许不得转载:堆上小栈 » Java和Python通过gRPC互相调用

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册