grcp入门使用(java)

grcp入门使用(java)

1.依赖

<dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.57.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.57.2</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.57.2</version>
        </dependency>
        <dependency> <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
<!--            protobuf插件 自动下载 重启idea-->
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.22.3:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.57.2: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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

说明:如果出现如下情况 则在properties中添加<os.detected.classifier>windows-x86_64</os.detected.classifier>

<properties>
    <os.detected.classifier>windows-x86_64</os.detected.classifier>
</properties>

在这里插入图片描述

创建完成后
在这里插入图片描述
在这里插入图片描述

2.创建目录导入proto文件

1.创建proto目录(与java目录同级) 并proto目录下创建.proto文件

在这里插入图片描述

2.proto文件内容

syntax = "proto3";

//java_multiple_files(文件选项):如果为false,.proto文件和所有的Java类、枚举等仅生成单个java文件。生成的顶层消息、服务和枚举将被内嵌到一个外部类中(参见java_outer_classname)。如果为true,每个Java类、枚举等将回生成一个单独的java文件。该.proto文件生成的顶层消息、服务、枚举和包装器java类将不会内嵌任何类、枚举等。这是一个默认值为false的布尔选项。如果不生成Java代码,该选项不起作用。
option java_multiple_files = true;
//用于生成Java类的包
option java_package = "io.grpc.examples.helloworld";
//要生成的java类的类名
option java_outer_classname = "HelloWorldProto";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}

  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}

  rpc sayTest (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;
}

3.proto文件解析

protoBuf相关内容可看protoBu入门贴 在次不做赘述

3.使用protobuf插件生成protobuf 代码和 grpc 代码

1.依次运行protobuf:compile 和protobuf:compile-custom

在这里插入图片描述

2.创建完成

创建完成后在target/generated-sources/protobuf/grpc-java下可以看到生成的代码 可再项目中直接引用
在这里插入图片描述

4.编写客户端及服务的代码

客户端

public class GrpcClient {

    public static void main(String[] args) throws InterruptedException {
        String host = "localhost";
        int port = 50051;
        ManagedChannel managedChannel = Grpc.newChannelBuilderForAddress(host, port, InsecureChannelCredentials.create()).build();
        GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(managedChannel);

        HelloRequest helloRequest = HelloRequest.newBuilder().setName("我是客户端").build();
        HelloReply reply = blockingStub.sayTest(helloRequest);
        System.out.println(reply.getMessage());

        managedChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
    }
}

服务端

public class GrpcServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 50051;
        Server server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create())
                .addService(new GreeterImpl())
                .build()
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            stopServer(server);
            
        }));
        server.awaitTermination();
    }

    private static void stopServer(Server server) {
        if (server != null) {
            server.shutdown();
        }
    }

    static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
        @Override
        public void sayTest(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            HelloReply reply = HelloReply.newBuilder().setMessage("我是服务端" + req.getName()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
}

测试时先运行服务端再运行客户端

在这里插入图片描述

在服务端代码中可加入拦截器等代码完善业务逻辑

待完善=======

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值