登录
    Technology changes quickly but people's minds change slowly.

利用grpc 实现java 服务与Python服务的互相调用

技术宅 破玉 1811次浏览 0个评论

    在使用grpc 之前,需要了解proto3 的语法,谷歌的官方教程如下(https://developers.google.cn/protocol-buffers/docs/javatutorial),我们就不再赘述。使用grpc我们需要定义.proto 文件,示例如下:

syntax = "proto3";
package com.magicdu.grpc.service;
// 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;
  }

上述文件主要定义的是接收消息的实体和返回消息的实体,利用代码生成器,我们便可以生成grpc 的代码
java 项目中需要引入如下依赖:

 <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.28.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.28.0</version>
        </dependency>+
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.28.0</version>
        </dependency>

然后加入编译插件:

  <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.11.0:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.28.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

将proto文件放到src/main 下面

然后打开maven工具,找到如下图所示的插件:

先执行protobuf:compile一遍,再执行protobuf:copile-custom,会自动生成文件,将生成的文件拷贝到对应的包中。
编写 java 客户端代码:

public class HelloClient {
    public static void main(String[] args) {
        String text="ip";
        final Channel messageChannel=NettyChannelBuilder.forAddress(SysConstants.IP,50051).negotiationType(NegotiationType.PLAINTEXT)
                .build();
       GreeterGrpc.GreeterBlockingStub stub= GreeterGrpc.newBlockingStub(messageChannel);
        Helloworld.HelloReply reply=stub.sayHello(Helloworld.HelloRequest.newBuilder().setName(text).build());
        System.out.println("client recevie"+reply.getMessage());
    }
}

再利用相同的proto 生成python 代码:

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

编写python 服务端代码:

from concurrent import futures
import grpc
import time
import helloworld_pb2
import helloworld_pb2_grpc
import requests
import json

def getIP():
    ip= requests.get("https://api.ipify.org/?format=json")
    ip=json.loads(ip.text)
    return ip['ip']

class Greeter(helloworld_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        responseMsg="127.0.0.1"
        name=request.name
        if(name=='ip'):
            responseMsg=getIP()
        return helloworld_pb2.HelloReply(message='IP, %s!' % responseMsg)



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(60*60*24) # one day in seconds
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    serve()

启动服务端,再启动java客户端,就实现 java 调用 python rpc 服务


华裳绕指柔, 版权所有丨如未注明 , 均为原创|转载请注明利用grpc 实现java 服务与Python服务的互相调用
喜欢 (0)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址