gRPC學習記錄(二)--Hello World
標簽(空格分隔): javaWEB
在上一篇的整體了解后,該篇則對應了快速上手,入門示例當然仍舊是Hello world,該一階段不需要深究代碼,所要求的的目的是先跑通,再回顧代碼,然后分析需要什么知識,再去學什么.
1.Maven配置
首先是三個依賴包
<properties>
<grpc.version>1.0.3</grpc.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
接著是轉換工具
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2.編寫proto文件
在main目錄下建立一個proto文件夾,然后在里面建立hello.proto,內容如下:
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// 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;
}
接下來執(zhí)行 mvn compile
,就會生成如下代碼,如果未被標記為源代碼目錄的話,就右鍵標記下:
3.編寫服務端代碼
public class HelloWorldServer {
private int port = 50051;
private Server server;
/**
* 啟動服務
* @throws IOException
*/
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
System.out.println("service start...");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
// block 一直到退出程序
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorldServer server = new HelloWorldServer();
server.start();
server.blockUntilShutdown();
}
// 實現(xiàn) 定義一個實現(xiàn)服務接口的類
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
//獲取參數(shù)
System.out.println("收到的信息:"+req.getName());
//這里可以放置具體業(yè)務處理代碼 start
//這里可以放置具體業(yè)務處理代碼 end
//構造返回
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
4.編寫客戶端代碼
public class HelloWorldClient {
private final ManagedChannel channel; //一個gRPC信道
private final GreeterGrpc.GreeterBlockingStub blockingStub;//阻塞/同步 存根
//初始化信道和存根
public HelloWorldClient(String host,int port){
this(ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext(true));
}
/** Construct client for accessing RouteGuide server using the existing channel. */
private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
//客戶端方法
public void greet(String name){
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
System.out.println("RPC調用失敗:"+e.getMessage());
return;
}
System.out.println("服務器返回信息:"+response.getMessage());
}
public static void main(String[] args) throws InterruptedException {
HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
try {
for(int i=0;i<5;i++){
client.greet("world:"+i);
}
}finally {
client.shutdown();
}
}
}
5.測試
服務端啟動后,客戶端訪問
客戶端:
服務端:
6.回顧分析
這一環(huán)節(jié)很重要,要對這個HelloWorld的Demo了解為什么跑通了.
回顧下在這個過程中做了哪些事情?
1.首先maven引入了三個依賴,分別是grpc-netty
,grpc-protobuf
,grpc-stub
.應該是通訊,序列化,客戶端調用三部分的東西吧.最后在build里面引入了一堆東西.
2.寫proto文件,大概就是定義了一個服務接口的輸入輸出類型,然后利用build里面的工具,生成一堆代碼.
//指定proto3格式
syntax = "proto3";
//一些生成代碼的設置
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
//定義了一個service
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
//定義了一個消息請求體
message HelloRequest {
string name = 1;
}
//定義了一個消息回復體
message HelloReply {
string message = 1;
}
3.編寫服務端
服務端有如下代碼,可以看出這個接口和proto里面定義的接口是一致的.
private class GreeterImpl extends GreeterGrpc.GreeterImplBase{
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {};
}
然后使用如下代碼把該service綁定,
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
4.編寫客戶端代碼
客戶端通過如下方法創(chuàng)建了一個通信信道,然后和一個阻塞同步的通訊工具blockingStub
.
//初始化信道和存根
public HelloWorldClient(String host,int port){
this(ManagedChannelBuilder.forAddress(host, port)
.usePlaintext(true));
}
private HelloWorldClient(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
然后通過該blockingStub
調用服務端方法.
//客戶端方法
public void greet(String name){
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
System.out.println("RPC調用失敗:"+e.getMessage());
return;
}
System.out.println("服務器返回信息:"+response.getMessage());
}
接下來很自然的就去學proto3的一些相關知識了.