在 Java 中使用 gRPC 和 ProtoBuf


  欢迎回到构建 Web 服务器系列。到目前为止,我们主要专注于在 GoLang 中编写 Web 服务器。但是,我收到了写一篇文章的请求,即如何使用 Java 完成 gRPC 实现以及实现相同目标的可用库和选项有哪些。

        先决条件:基本了解SpringSpring BootDependency InjectionRPC 和 ProtoBuf

  我们将使用 spring boot 来初始化一个基本服务,然后在它上面添加一个 RPC 服务器和客户端。

 编写 Java gRPC 服务器的步骤

 1. 编写原型定义

// 将以下依赖项添加到依赖项部分。此依赖项可帮助您使用 io.grpc 模块开箱即用地运行基本的 GRPC 服务器。
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-server-spring-boot-autoconfigure</artifactId>
<version>2.12.0.RELEASE</version>
</dependency>//将以下扩展添加到构建部分。此扩展在 protobuf 编译步骤期间添加了操作系统特定的逻辑。
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os-maven-plugin.version}</version>
</extension >
</扩展>// 将以下插件添加到构建部分。该插件编译 protobuf 文件并将其添加到目标文件夹中。
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
< protocArtifact>
com.google.protobuf: protoc :3.3.0:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc -java:1.4.0:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>


<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>// 将以下内容添加到属性部分
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
<os-maven-plugin.version>1.6.1</os-maven-plugin.版本>


  对pom.xml文件进行更改后,运行mvn clean install以编译代码并从 protobuf 定义生成所需的样板 Java 代码。

  2.你好世界服务器

接下来,我们需要初始化服务器并注册我们的 gRPC 服务实现。将您的GrpcServerApplication.java文件修改为如下所示:
@SpringBootApplication
public class GrpcServerApplication {

public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder. forPort(8080)
.addService(新HelloServiceImpl())构建()。

系统。out .println("正在启动服务器...");
server.start();
系统。out .println("服务器启动了!");
server.awaitTermination();
}

}
  在上面的文件中,我们在端口上创建了一个新的 gRPC 服务器8080并注册我们HelloServiceImpl的。

  3. 编译和测试




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM