gRpc JAVA应用实例

gRpc JAVA应用实例

(1)添加maven依赖

pom.xml中添加:

<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.17.1</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.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <skipTests>true</skipTests>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!--在这里修改版本-->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.7</version>
        </plugin>
        <plugin>
            <groupId>org.xolstice.maven.plugins</groupId>
            <artifactId>protobuf-maven-plugin</artifactId>
            <version>0.5.0</version>
            <configuration>
                <protocArtifact>com.google.protobuf:protoc:3.4.0:exe:${os.detected.classifier}</protocArtifact>
                <pluginId>grpc-java</pluginId>
                <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.7.0:exe:${os.detected.classifier}</pluginArtifact>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>compile-custom</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
(2)定制服务
  1. 新建文件src/main/proto/test.proto
syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.example.demo.proto";
option java_outer_classname = "HelloProto";

package com.acupt.grpc;

service HelloService {
  rpc hello (InvokeRequest) returns (InvokeResponse) {}

}

message InvokeRequest {
  string name = 1;
}

message InvokeResponse {
  string msg = 1;
}
  1. 构建,编译proto文件

    执行后可在项目目录/target/generated-sources/protobuf目录下找到生成的Java文件,用这些代码可以实现gRPC远程调用。

    但在项目中还无法直接引用上面的类,右键target -> Mark Directory as -> Generated Sources Root,,然后就可以在项目中引用了。
(3)使用
  1. 编写服务实现类
package com.example.demo.grpc;

import com.example.demo.proto.HelloServiceGrpc;
import com.example.demo.proto.InvokeRequest;
import com.example.demo.proto.InvokeResponse;
import io.grpc.stub.StreamObserver;

/**
 1. 服务实现类
 */
public class HelloService extends HelloServiceGrpc.HelloServiceImplBase {

    @Override
    public void hello(InvokeRequest request, StreamObserver<InvokeResponse> responseObserver) {
        System.out.println("request -> " + request);
        String name = request.getName();//自定义的字段名 name
        InvokeResponse response = InvokeResponse.newBuilder()
                .setMsg("hello," + name)//自定义的字段名 msg
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }
}
  1. 编写服务器端
package com.example.demo.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

/**
 1. 服务提供方
*/
public class MyServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 50051;
        Server server = ServerBuilder.forPort(port)
                .addService(new HelloService())
                .build()
                .start();
        System.out.println("started");

        server.awaitTermination();
//        Thread.sleep(1000 * 60 * 2);
//        server.shutdown();
//        System.out.println("shutdown");
    }
}
  1. 客户端
package com.example.demo.grpc;

import com.example.demo.proto.HelloServiceGrpc;
import com.example.demo.proto.InvokeRequest;
import com.example.demo.proto.InvokeResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 服务调用方
 */
public class MyClient {

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        InvokeRequest request = InvokeRequest.newBuilder().setName("tom").build();
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext(true).build();
        HelloServiceGrpc.HelloServiceBlockingStub blockingStub = HelloServiceGrpc.newBlockingStub(channel);
        InvokeResponse response = blockingStub.hello(request);
        System.out.println(response.getMsg());

        //客户端程序结束后,服务端报java.io.IOException: 远程主机强迫关闭了一个现有的连接。
        //grpc managedChannel.shutdown
        channel.shutdown().awaitTermination(1, TimeUnit.SECONDS);
//        channel.shutdown();

//        HelloServiceGrpc.HelloServiceFutureStub futureStub = HelloServiceGrpc.newFutureStub(channel);
//        ListenableFuture<InvokeResponse> future = futureStub.hello(request);
//        future.addListener(
//                () -> System.out.println("listener 1"),
//                command -> {
//                    System.out.println("execute 1 " + command);
//                    command.run();
//                });
//        future.addListener(
//                () -> System.out.println("listener 2"),
//                command -> {
//                    System.out.println("execute 2 " + command);
//                    command.run();
//                });
//
//        System.out.println(future.get(10, TimeUnit.SECONDS));

    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

anjushi_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值