gRPC Java 不支持在Android设备上运行server端,所以本文所讲解案例是Client端运行在Android 设备,而服务端运行在本地电脑端。
# Clone the repository at the latest release to get the example code:
$ git clone -b v1.29.0 https://github.com/grpc/grpc-java
# Navigate to the Java examples:
$ cd grpc-java/examples
此次下载的是所有的grpc Java相关的源码,我们仅用其examples源码
编译服务器:
$ ./gradlew installDist
运行服务器:
$ ./build/install/examples/bin/hello-world-server
五月 04, 2020 9:11:21 下午 io.grpc.examples.helloworld.HelloWorldServer start
信息: Server started, listening on 50051
上面运行服务端的终端不要关闭,重新另外打开一个新的终端,连接一个Android设备,然后执行下面命令:
$ cd android/helloworld
$ ../../gradlew installDebug
补充: 我在本地编译时下载proto插件会失败,修改了build.gradle文件如下:
repositories {
google()
jcenter()
mavenCentral()
maven { // The google mirror is less flaky than mavenCentral()
url "https://maven-central.storage-download.googleapis.com/repos/central/data/" }
mavenLocal()
}
gRPC是通过protobuf来定义的,服务端和客户端都有一个SayHello RPC方法,会从客户端获取HelloRequest参数,并且从服务端返回HelloResponse参数,定义内容如下:
// 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;
}
让我们在Greeter下在添加一个新的方法SayHelloAgain,打开src/main/proto/helloworld.proto
,在里面添加SayHelloAgain方法如下所示:
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (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;
}
打开 src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java
,添加修改如下:
private class GreeterImpl 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();
}
@Override
public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
打开app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java
,添加修改如下:
try {
HelloRequest message = HelloRequest.newBuilder().setName(mMessage).build();
HelloReply reply = stub.sayHello(message);
reply = stub.sayHelloAgain(message);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
return "Failed... : " + System.lineSeparator() + sw;
}
重复 第二步 运行gRPC应用:
$ ./gradlew installDist
$ ./build/install/examples/bin/hello-world-server
$ cd android/helloworld
$ ../../gradlew installDebug