代碼已上傳代碼倉庫GITHUB:https://github.com/LynHB/ProjectA/tree/master/src/main/java/study/grpc
工具準(zhǔn)備
1.通過proto文件生成java類
命令:
[protobuf exe path] --java_out=[需要生成java的位置]
protoc.exe ./TestUser.proto --java_out=./
2.通過proto文件生成java grpc類
命令:
[protobuf exe path] --plugin=[protoc-gen-grpc-java exe path] --grpc-java_out=[需要生成java的位置] [proto文件位置]
D:\protobuf\bin\protoc --plugin=protoc-gen-grpc-java=D:\protobuf\bin\protoc-gen-grpc-java-1.30.2-windows-x86_64.exe --grpc-java_out=./ ./scheduler.proto
3 Java maven 依賴
<properties>
<grpc.version>1.30.2</grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
4.Server端編寫
4.1 編寫protobuf文件
下面是定義一個簡單的protobuf grpc文件,service塊內(nèi)定義調(diào)用的function钥平,message定義的是結(jié)構(gòu)體。
syntax = "proto3";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (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;
}
4.2 創(chuàng)建grpc和protobuf java類
先根據(jù)1和2生成對應(yīng)的實體和rpc服務(wù)類
cd D:\IDEAData\ProjectA1\src\main\java\study\grpc\proto\
D:\IDEAData\ProjectA1\src\main\java\study\grpc\proto>D:\protobuf\bin\protoc --plugin=protoc-gen-grpc-java=D:\protobuf\bin\protoc-gen-grpc-java-1.30.2-windows-x86_64.exe --grpc-java_out=./ Greeter.proto
D:\protobuf\bin\protoc --java_out=./ Greeter.proto
GreeterOuterClass和GreeterGrpc就是對應(yīng)命令生成的java文件。
4.3 編寫GreeterServiceImpl
package study.grpc.service;
import io.grpc.stub.StreamObserver;
import study.grpc.pojo.GreeterOuterClass.*;
import study.grpc.rpc.GreeterGrpc;
/**
* @Author LynHB
* @Description : grpc實現(xiàn)接口
* @Date 19:53 2020/7/29
**/
public class GreeterServiceImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
4.4 編寫Server入口類
package study.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.log4j.Log4j2;
import study.grpc.service.GreeterServiceImpl;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @Author LynHB
* @Description :g rpc server入口類
* @Date 19:55 2020/7/29
**/
@Log4j2
public class ServerMain {
private final int port;
private final Server server;
public ServerMain(int port){
this.port = port;
/*
* 創(chuàng)建Server
* addService()添加對應(yīng)的服務(wù)
* forPort()指定端口
*/
this.server = ServerBuilder.forPort(port).addService(new GreeterServiceImpl()).build();
}
public void start() throws IOException{
server.start();
log.info("Started server listening on " + port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
ServerMain.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
log.error("Server shut down.");
}));
}
public void stop() throws InterruptedException{
if(server != null){
server.shutdown().awaitTermination(30,TimeUnit.SECONDS);
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
ServerMain server = new ServerMain(10000);
server.start();
server.blockUntilShutdown();
}
}
4.5 啟動Server
5.Client端編寫
package study.grpc;
import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.internal.ClientStream;
import lombok.extern.log4j.Log4j2;
import study.grpc.pojo.GreeterOuterClass.*;
import study.grpc.rpc.GreeterGrpc.*;
import java.util.concurrent.TimeUnit;
import static study.grpc.rpc.GreeterGrpc.newBlockingStub;
/**
* @Author LynHB
* @Description : g rpc 客戶端入口類
* @Date 19:56 2020/7/29
**/
@Log4j2
public class ClientMain {
private final GreeterBlockingStub blockingStub;
private final ManagedChannel managedChannel;
public ClientMain(String ip,int port) {
this.managedChannel = ManagedChannelBuilder.forTarget(ip+":"+port).usePlaintext().build();
this.blockingStub = newBlockingStub(this.managedChannel);
log.info("Connected to server at "+ip+":"+port);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
this.managedChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("Client shut down.");
}));
}
private void shutdown() throws InterruptedException {
this.managedChannel.shutdown().awaitTermination(5L, TimeUnit.SECONDS);
}
public static void main(String[] args) throws InterruptedException {
ClientMain clientMain = new ClientMain("0.0.0.0",10000);
HelloReply helloReply = clientMain.blockingStub.sayHello(HelloRequest.newBuilder().setName("測試").build());
log.info(helloReply.getMessage());
clientMain.shutdown();
}
}