今天来记录一下用Java实现protobuf+GRPC实现数据传输。
概念性的内容就不在这里说了,直接上代码。
1.项目依赖,添加了依赖之后才能通过.proto文件进行生成grpc代码。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.11.RELEASE</version>
<relativePath/>
</parent>
<groupId>org.example</groupId>
<artifactId>grpc</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.12.0</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<!--<plugin>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-maven-plugin</artifactId>-->
<!--</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerVersion>${java.version}</compilerVersion>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
2.需要有一个.proto文件用来定义数据格式和传输方法
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.yueyue.grpc";
option java_outer_classname = "TestProto";
option objc_class_prefix = "WY";
package onlytest;
//定义服务
service TestGreeter {
//注意:这里是returns 不是return
rpc TestSomeThing (TestRequest) returns (TestResponse) {
}
}
//定义消息类型
message TestRequest {
string name = 1;
string age = 20;
}
message TestResponse {
string message = 1;
}
3.执行maven -compile 命令,博主这里是在idea中执行的
4.服务端代码,通过main方法直接启动。
package com.yueyue.test.protobuf.server;
import com.yueyue.grpc.TestGreeterGrpc;
import com.yueyue.grpc.TestRequest;
import com.yueyue.grpc.TestResponse;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
/**
* 服务端
*/
public class TestServer {
//定义端口
private final int port = 50051;
//服务
private Server server;
//启动服务,并且接受请求
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.addService(new GreeterImpl())
.build().start();
System.out.println("服务开始启动-------");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("------关闭服务-------");
TestServer.this.stop();
System.err.println("------服务关闭------");
}
});
}
//stop服务
private void stop() {
if (server != null) {
server.shutdown();
}
}
//server阻塞到程序退出
private void blockUntilShutdown() throws InterruptedException {
if (server!=null){
server.awaitTermination();
}
}
//实现服务接口的类
private class GreeterImpl extends TestGreeterGrpc.TestGreeterImplBase {
public void testSomeThing(TestRequest request, StreamObserver<TestResponse> responseObserver) {
System.out.println("接收到数据:" +request );
TestResponse build = TestResponse.newBuilder().setMessage(request.getName()).build();
//onNext()方法向客户端返回结果
responseObserver.onNext(build);
//告诉客户端这次调用已经完成
responseObserver.onCompleted();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final TestServer server=new TestServer();
server.start();
server.blockUntilShutdown();
}
}
5.客户端代码
package com.yueyue.test.protobuf.client;
import com.yueyue.grpc.TestGreeterGrpc;
import com.yueyue.grpc.TestRequest;
import com.yueyue.grpc.TestResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.concurrent.TimeUnit;
/**
* 客户端
*/
public class TestClient {
private final ManagedChannel channel;
private final TestGreeterGrpc.TestGreeterBlockingStub blockingStub;
private static final String host = "127.0.0.1";
private static final int ip = 50051;
public TestClient(String host, int port) {
//usePlaintext表示明文传输,否则需要配置ssl
//channel 表示通信通道
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
//存根
blockingStub = TestGreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void testResult(String name) {
TestRequest request = TestRequest.newBuilder().setName(name).build();
TestResponse response = blockingStub.testSomeThing(request);
System.out.println("接收到返回值:"+response.getMessage());
}
public static void main(String[] args) {
TestClient client = new TestClient(host, ip);
for (int i = 0; i < 5; i++) {
client.testResult("数据" + i);
}
}
}
6.测试,先启动server,再启动客户端代码。
搞定!
博主已经将代码上传到gitee上了 ,博友们可以自行下载,这么良心的博主已经很少见了!