Java实现protobuf+GRPC实现数据传输

今天来记录一下用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上了 ,博友们可以自行下载,这么良心的博主已经很少见了!

代码git地址:https://gitee.com/840312696/protobuf-grpc.git

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值