<?xml version="1.0" enCoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter-parent</artifactID> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupID>com.grpc</groupID> <artifactID>server</artifactID> <version>0.0.1-SNAPSHOT</version> <name>java_server</name> <description>JAVa的grpc端</description> <propertIEs> <java.version>11</java.version> </propertIEs> <dependencIEs> <dependency> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter</artifactID> </dependency> <dependency> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter-test</artifactID> <scope>test</scope> </dependency> <dependency> <groupID>io.grpc</groupID> <artifactID>grpc-netty-shaded</artifactID> <version>1.26.0</version> </dependency> <dependency> <groupID>io.grpc</groupID> <artifactID>grpc-protobuf</artifactID> <version>1.26.0</version> </dependency> <dependency> <groupID>io.grpc</groupID> <artifactID>grpc-stub</artifactID> <version>1.26.0</version> </dependency> <!-- lombok插件--> <dependency> <groupID>org.projectlombok</groupID> <artifactID>lombok</artifactID> <optional>true</optional> </dependency> </dependencIEs> <build> <extensions> <extension> <groupID>kr.motd.maven</groupID> <artifactID>os-maven-plugin</artifactID> <version>1.6.2</version> </extension> </extensions> <plugins> <plugin> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-maven-plugin</artifactID> </plugin> <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.26.0:exe:${os.detected.classifIEr}</pluginArtifact> <!--默认值--> <protoSourceRoot>${project.basedir}/src/main/resources/proto</protoSourceRoot> <outputDirectory>${project.basedir}/src/main/java/com/grpc/shiyun</outputDirectory> <!--设置是否在生成java文件之前清空outputDirectory的文件,默认值为true,设置为false时也会覆盖同名文件--> <clearOutputDirectory>true</clearOutputDirectory> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> </goals> </execution> </executions> </plugin> </plugins> </build></project>
1.2书写proto文件autochat.protoSyntax = "proto3";option java_multiple_files = true;package shiyun;// The greeting service deFinition.service Autochat { // Sends a greeting rpc autochat (AutochatRequest) returns (AutochatReply) {}}// The request message containing the user's name.message AutochatRequest { string question = 1;}// The response message containing the greetingsmessage AutochatReply { string response = 1;}
1.3使用protobuf插件生成Java代码首先点击compile命令生成代码,然后再点击compile-custom生成代码,分两次生成。
2.使用Python生成代码2.1安装protobufpip install grpcio
2.2使用 protoc 编译 proto 文件, 生成 python 语言的实现# 安装 python 下的 protoc 编译器pip install grpcio-tools
2.3编写autochat.proto文件(和Java的一致)Syntax = "proto3";#在Python时候不需要这个选项#option java_multiple_files = true;package shiyun;// The greeting service deFinition.service Autochat { // Sends a greeting rpc autochat (AutochatRequest) returns (AutochatReply) {}}// The request message containing the user's name.message AutochatRequest { string question = 1;}// The response message containing the greetingsmessage AutochatReply { string response = 1;}
2.4编译文件# 编译 proto 文件python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. autochat.proto
python -m grpc_tools.protoc: python 下的 protoc 编译器通过 python 模块(module) 实现, 所以说这一步非常省心
–python_out=. : 编译生成处理 protobuf 相关的代码的路径, 这里生成到当前目录
**–grpc_python_out=. : 编译生成处理 grpc 相关的代码的路径
-I. autochat.proto : proto 文件的路径, 这里的 proto 文件在当前目录
3.编写Java客户端代码package com.grpc.clIEnt;import io.grpc.ManagedChannel;import io.grpc.ManagedChannelBuilder;import io.grpc.StatusRuntimeException;import shiyun.AutochatRequest;import java.util.concurrent.TimeUnit;import java.util.logging.Level;import java.util.logging.Logger;public class AutochatClIEnt { private static final Logger logger = Logger.getLogger(AutochatClIEnt.class.getname()); private final ManagedChannel channel; private final shiyun.AutochatGrpc.AutochatBlockingStub blockingStub; /** * Construct clIEnt connecting to HelloWorld server at {@code host:port}. */ public AutochatClIEnt(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoID // needing certificates. .usePlaintext() .build()); } /** * Construct clIEnt for accessing HelloWorld server using the existing channel. */ AutochatClIEnt(ManagedChannel channel) { this.channel = channel; blockingStub = shiyun.AutochatGrpc.newBlockingStub(channel); } public voID shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } /** * Say hello to server. */ public voID sendQuestion(String question) { AutochatRequest request = shiyun.AutochatRequest.newBuilder().setQuestion(question).build(); shiyun.AutochatReply response; try { response = blockingStub.autochat(request); logger.info("接收来自服务器的响应: " + response.getResponse()); } catch (StatusRuntimeException e) { logger.log(Level.WARNING, "RPC Failed: {0}", e.getStatus()); return; } } /** * Greet server. If provIDed, the first element of {@code args} is the name to use in the * greeting. */ public static voID main(String[] args) throws Exception { // Access a service running on the local machine on port 50052 AutochatClIEnt clIEnt = new AutochatClIEnt("localhost", 50052); try { String user = "world"; // Use the arg as the name to greet if provIDed if (args.length > 0) { user = args[0]; } int i = 0 ; while (true){ clIEnt.sendQuestion(user+i++); Thread.sleep(1000); } } finally { clIEnt.shutdown(); } }}
4.Python服务端代码from concurrent import futuresimport timeimport grpc# 实现 proto 文件中定义的 AutochatServicerimport autochat_pb2_grpc, autochat_pb2_ONE_DAY_IN_SECONDS = 60 * 60 * 24class AutochatServer(autochat_pb2_grpc.AutochatServicer): def autochat(self, request, context): print("接收到客户端消息:" + request.question) return autochat_pb2.AutochatReply(response= request.question)def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) autochat_pb2_grpc.add_AutochatServicer_to_server(AutochatServer(), server) server.add_insecure_port('[::]:50052') print("启动服务器等待连接。。。。") server.start() try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0)if __name__ == '__main__': serve()
5.项目源代码已经同步到GitHub和gitee,如有需要请移步自行下载:gitee: https://gitee.com/ljf2402901363/grpc.gitgithub: https://github.com/LJF2402901363/grpc.git6.本博客已同步到个人博客,如有需要请移步:http://moyisuiying.com/index.php/javastudy/springboot/479.html
总结以上是内存溢出为你收集整理的JAVA和Python的GRPC远程调用全部内容,希望文章能够帮你解决JAVA和Python的GRPC远程调用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)