通过Spring Boot创建Java项目,pom.xml中加入如下依赖
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
io.grpc
grpc-netty-shaded
1.21.0
io.grpc
grpc-protobuf
1.21.0
io.grpc
grpc-stub
1.21.0
kr.motd.maven
os-maven-plugin
1.5.0.Final
org.xolstice.maven.plugins
protobuf-maven-plugin
0.5.1
com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}
grpc-java
io.grpc:protoc-gen-grpc-java:1.21.0:exe:${os.detected.classifier}
src/main/java
false
compile
compile-custom
org.springframework.boot
spring-boot-maven-plugin
定义IDL文件
syntax = "proto3";
option java_multiple_files = true;
option java_package = "net.changjinglu.proto";
option java_outer_classname = "TelegraphProto";
package telegraph;
// The greeting service definition.
service TelegraphService {
// Sends a greeting
rpc SayLove (LoveRequest) returns (LoveReply) {}
}
// The request message containing the user's name.
message LoveRequest {
string message = 1;
}
// The response message containing the greetings
message LoveReply {
string message = 1;
}
编译生成IDL定义的Java服务接口,相关代码会生成到配置对应的路径下
mvn clean install
实现IDL定义的Java服务接口
public class TelegraphGreeterImpl extends TelegraphServiceGrpc.TelegraphServiceImplBase {
@Override
public void sayLove(LoveRequest request, StreamObserver responseObserver) {
System.out.println("收到Node小怪兽的消息:"+request.getMessage());
responseObserver.onNext(LoveReply.newBuilder().setMessage("I Love U Too").build());
//结束
responseObserver.onCompleted();
}
}
编写并启动Java服务端
public class GrpcServer {
/** GRPC 服务端 */
private Server server;
public static void main(String[] args) throws IOException, InterruptedException {
GrpcServer grpcService = new GrpcServer();
grpcService.start();
System.out.println("GRPC 服务端启动成功");
//GRPC 服务端需要手动阻塞线程
grpcService.waitTermination();
}
private void start() throws IOException {
//绑定接口、启动服务
this.server = ServerBuilder.forPort(8899)
.addService(new TelegraphGreeterImpl())
.build()
.start();
System.out.println("server start!");
//这里是为了防止jvm关闭了,但是tcp还没有关闭的情况
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("关闭jvm");
GrpcServer.this.stop();
}));
}
private void stop() {
if (this.server != null) {
this.server.shutdown();
}
}
private void waitTermination() throws InterruptedException {
if (this.server != null) {
server.awaitTermination();
}
}
}
编写并启动Nodejs客户端,客户端使用相同的IDL
var PROTO_FILE_PATH = '/Users/wenyuan/Nodejs/grpc/proto/telegraph.proto';
var grpc = require('grpc');
var grpcService = grpc.load(PROTO_FILE_PATH).telegraph;
function main() {
var stub = new grpcService.TelegraphService('localhost:8899',grpc.credentials.createInsecure());
stub.sayLove({message:'今晚的月色真美'},function (error, result) {
console.log('收到Java小怪兽的消息: ' + result.message);
});
}
main();
Java服务端收到消息并回复
Nodejs客户端收到Java服务端的回复