前言
经常看到说gRPC怎么好的文章,实际工作中也没有体验过,这次看了一下它的HelloWorld程序,记录一下这个过程。 RPC是Remote Produce Call 的缩写, 就是远程调用,调用远程的代码像本地一样。Java里面比较有名的RPC框架Dubbo,但它只支持Java。 gRPC 是google开源的RPC框架,使用HTTP2, 支持很多种语言:Java,GO,.Net Core,C,它都有对应的支持。 这篇初体验就打算使用Java做服务端,分别使用Java和GO作为客户端。
Java服务端和客户端
首先我们来建一个Java服务端。
使用gRPC最基础的一步是protobuf文件,这里我们直接使用HelloWorld里面的文件,首先新建一个helloworld.proto在source目录下面,参考了这篇文章https://www.cnblogs.com/liugh/p/7505533.html
syntax = "proto3";
option java_multiple_files = true;
option java_package = "ken.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// 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;
}
定义了一个SayHello方法,接收HelloRequest的消息,返回HelloReply
我们用proto文件生成相应的Java代码
这里我们直接使用maven插件protobuf-maven-plugin来完成,
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.4.1</version>
<executions>
<execution>
<id>enforce</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireUpperBoundDeps/>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
这样编译之后
就会生成对应的Java文件在target目录下面
然后就是新建一个HelloWorldServer来作为服务端,这里代码省略,可以直接使用
https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java
IDEA会出现找不到类的错误,重启一下IEDA可以修复
POM文件需要添加grpc-netty-shaded,grpc-protobuf,grpc-stub,protobuf-java-util,gson 参考grpc的sample就可以了,客户端也是这样的配置
客户端代码同样也是需要用Propo文件生成Java类,然后添加POM文件,然后编写客户端代码
https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java
运行服务端Java类, 控制台输出
INFO: Server started, listening on 50051
然后运行客户端代码