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)定制服务
- 新建文件
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;
}
- 构建,编译proto文件
执行后可在项目目录/target/generated-sources/protobuf
目录下找到生成的Java文件,用这些代码可以实现gRPC远程调用。
但在项目中还无法直接引用上面的类,右键target -> Mark Directory as -> Generated Sources Root,
,然后就可以在项目中引用了。
(3)使用
- 编写服务实现类
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();
}
}
- 编写服务器端
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");
}
}
- 客户端
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));
}
}