gRPC 可以像调用方法一样进行网络请求
github地址:https://github.com/grpc/grpc-java
使用:
1.proto文件放置到 src/main/proto
2. 根目录gradle
classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.17"
- module gradle配置
plugins {
...
id 'com.google.protobuf'
}
android {
...
}
protobuf {
protoc { artifact = 'com.google.protobuf:protoc:3.17.2' }
plugins {
grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.40.0' // CURRENT_GRPC_VERSION
}
}
generateProtoTasks {
all().each { task ->
task.builtins {
java { option 'lite' }
}
task.plugins {
grpc { // Options added to --grpc_out
option 'lite' }
}
}
}
}
dependencies {
//gRPC
implementation 'io.grpc:grpc-okhttp:1.40.0' // CURRENT_GRPC_VERSION
implementation 'io.grpc:grpc-protobuf-lite:1.40.0' // CURRENT_GRPC_VERSION
implementation 'io.grpc:grpc-stub:1.40.0' // CURRENT_GRPC_VERSION
compileonly 'org.apache.tomcat:annotations-api:6.0.53'
implementation project(':common')
}
- 简单使用(伪代码)
//创建channel ManagedChannel channel = ManagedChannelBuilder.forAddress(ip, port).usePlaintext().build(); //创建阻塞请求服务 ServiceBlockingStub serviceBlockingStub = ServiceGrpc.newBlockingStub(channel); //创建请求 Request request = Request.newBuilder().build(); //调用服务getData方法 serviceBlockingStub.getData(request);
- stream接收(伪代码)
//创建channel ManagedChannel channel = ManagedChannelBuilder.forAddress(ip, port).usePlaintext().build(); //创建请求服务 ServiceBlockingStub serviceBlockingStub = ServiceGrpc.newStub(channel); //创建请求 Request request = Request.newBuilder().build(); //调用服务getData方法, 并设置回调 serviceBlockingStub.getData(request, new StreamObserver() { @Override public void onNext(Data data) { Logger.e("Stream", "onNext"); } @Override public void onError(Throwable t) { Logger.e("Stream", "onError"); } @Override public void onCompleted() { Logger.e("Stream", "onCompleted"); } });



