gRPC(三)java gRPC样例

举报
张俭 发表于 2023/12/29 17:54:08 2023/12/29
【摘要】 本文代码地址https://gitee.com/shoothzj/grpc-examples java语言实现gRPC客户端服务端 添加依赖 <dependencies> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty-shaded</artifac...

本文代码地址

https://gitee.com/shoothzj/grpc-examples

java语言实现gRPC客户端服务端

添加依赖

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.47.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.47.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.47.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </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.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.19.2:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.47.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

书写proto文件

proto文件就用上述的定义,放置在src/main/proto文件夹下,如下图
image.png

书写server侧代码

package com.github.shoothzj.grpc.example;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

public class EchoServer {

    public static void main(String[] args) throws Exception {
        int port = 10240;
        Server server = ServerBuilder.forPort(port)
                .addService(new EchoImpl())
                .build()
                .start();
        server.awaitTermination();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            try {
                server.shutdown();
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
            System.err.println("*** server shut down");
        }));
    }

    static class EchoImpl extends EchoProto2ServiceGrpc.EchoProto2ServiceImplBase {

        @Override
        public void echoProto2(MessageProto2.EchoProto2Req request, StreamObserver<MessageProto2.EchoProto2Resp> responseObserver) {
            MessageProto2.EchoProto2Resp.Builder builder = MessageProto2.EchoProto2Resp.newBuilder();
            builder.setStrReq(request.getStrReq());
            builder.setStrOpt(request.getStrOpt());
            request.getStrRepList().forEach(builder::addStrRep);
            builder.setInt64Req(request.getInt64Req());
            builder.setInt32Opt(request.getInt32Opt());
            builder.setComic(request.getComic());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

}

client侧代码

package com.github.shoothzj.grpc.example;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

public class EchoClient {

    public static void main(String[] args) {
        String target = "localhost:10240";
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                .usePlaintext()
                .build();
        EchoProto2ServiceGrpc.EchoProto2ServiceBlockingStub blockingStub = EchoProto2ServiceGrpc.newBlockingStub(channel);
        MessageProto2.EchoProto2Req request = MessageProto2.EchoProto2Req.newBuilder()
                .setStrReq("strReq")
                .setStrOpt("strOpt")
                .addStrRep("str")
                .addStrRep("rep")
                .setInt64Req(1)
                .setInt32Opt(2)
                .setComic(MessageProto2.Comic.Bleach)
                .build();
        MessageProto2.EchoProto2Resp echoProto2Resp = blockingStub.echoProto2(request);
        System.out.println(echoProto2Resp);
    }

}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。