gRPC(三)java gRPC样例

2022-07-08  本文已影响0人  ShootHzj

本文代码地址

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);
    }

}
上一篇下一篇

猜你喜欢

热点阅读