gRPC是由Google主導(dǎo)開(kāi)發(fā)的RPC框架余舶,使用HTTP/2協(xié)議并用ProtoBuf作為序列化工具兔簇。其客戶端提供Objective-C发绢、Java接口,服務(wù)器側(cè)則有Java垄琐、Golang边酒、C++等接口,從而為移動(dòng)端(iOS/Androi)到服務(wù)器端通訊提供了一種解決方案狸窘。 當(dāng)然在當(dāng)下的環(huán)境下墩朦,這種解決方案更熱門(mén)的方式是RESTFull API接口。該方式需要自己去選擇編碼方式翻擒、服務(wù)器架構(gòu)氓涣、自己搭建框架(JSON-RPC)。gRPC官方對(duì)REST的聲音是:
和REST一樣遵循HTTP協(xié)議(明確的說(shuō)是HTTP/2)陋气,但是gRPC提供了全雙工流
和傳統(tǒng)的REST不同的是gRPC使用了靜態(tài)路徑劳吠,從而提高性能
用一些格式化的錯(cuò)誤碼代替了HTTP的狀態(tài)碼更好的標(biāo)示錯(cuò)誤
至于是否要選擇用gRPC。對(duì)于已經(jīng)有一套方案的團(tuán)隊(duì)巩趁,可以參考下赴背。如果是從頭來(lái)做,可以考慮下gRPC提供的從客戶端到服務(wù)器的整套解決方案,這樣不用客戶端去實(shí)現(xiàn)http的請(qǐng)求會(huì)話凰荚,JSON等的解析燃观,服務(wù)器端也有現(xiàn)成的框架用。從15年3月到現(xiàn)在gRPC也發(fā)展了一年了便瑟,慢慢趨于成熟缆毁。下面我們就以gRPC的Golang版本看下其在golang上面的表現(xiàn)。至于服務(wù)端的RPC到涂,感覺(jué)golang標(biāo)準(zhǔn)庫(kù)的RPC框架基本夠用了,沒(méi)必要再去用另一套方案脊框。
最近google發(fā)布了grpc1.0,之前一直關(guān)注過(guò)grpc践啄,數(shù)據(jù)交互使用了protocol buffer,相比之前使用的hession和json序列化方式性能應(yīng)該提升不少浇雹,所有先搞一個(gè)grpc的hello world跑一下,項(xiàng)目使用maven搭建,并使用idea開(kāi)發(fā)屿讽。
使用idea創(chuàng)建maven項(xiàng)目昭灵,添加pom配置
<a name="t2"></a>添加grpc1.0 maven依賴
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.0.0</version>
</dependency>
配置protobuf maven插件
配置了protobuf 插件后,可以自動(dòng)將.proto文件生成對(duì)應(yīng)的java代碼
<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.0.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
編寫(xiě)proto文件 helloworld.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;
}
編寫(xiě)grpc 服務(wù)端HelloWorldServer.java
package com;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
public class HelloWorldServer {
private int port = 50051;
private Server server;
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();
}
// 實(shí)現(xiàn) 定義一個(gè)實(shí)現(xiàn)服務(wù)接口的類(lèi)
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("service:"+req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
編寫(xiě)grpc 客戶端 HelloWorldClient.java
package com;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.util.concurrent.TimeUnit;
public class HelloWorldClient {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public HelloWorldClient(String host,int port){
channel = ManagedChannelBuilder.forAddress(host,port)
.usePlaintext(true)
.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 = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public static void main(String[] args) throws InterruptedException {
HelloWorldClient client = new HelloWorldClient("127.0.0.1",50051);
for(int i=0;i<5;i++){
client.greet("world:"+i);
}
}
}