代码已上传代码仓库GITHUB:https://github.com/LynHB/ProjectA/tree/master/src/main/java/study/grpc
工具准备
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块内定义调用的function,message定义的是结构体。
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 创建grpc和protobuf java类
先根据1和2生成对应的实体和rpc服务类
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就是对应命令生成的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实现接口
* @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;
/*
* 创建Server
* addService()添加对应的服务
* 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();
}
}