gRPC基础

什么是grpc

grpc创建一个服务接口,指定调用远程方法所需的参数和返回类型。

  • 服务端:实现服务的接口,启动一个服务器来处理客户端的调用。
  • 客户端:桩代码,提供与服务端相同的方法。

客户端与服务端可在不同环境下相互调用。

grpc默认采用protocol buffers(协议缓冲),这是用于数据结构序列化的框架。

使用

编写.proto文件,定义想要序列化的结构数据。

protocol buffers的数据是一个结构化的消息,每个消息都是一小的逻辑信息的记录,消息中包含了一系列的键值对,称之为属性,例如:

message Person {
   string name = 1;
   int32 age = 2;
   bool has_ponycopter = 3;       
}

然后用编译命令protoc来生成某个语言对应的类。

类中提供了简单的方法来操作每个属性(例如name()和set_name()), 另外这些方法内部可以将数据序列化为元数据传输给对方,也可以将对方发送过来的元数据进行解析。拿一个具体的例子来说,如果你使用的是c++,编译如上的例子后会生成一个叫做Person的类,你可以使用这个类来构建,序列化,并且得到 Person对应的protocol buffers消息。

更详细的例子,在proto文件中定义grpc服务,rpc的方法的参数和返回类型需要声明为一个protocols buffers消息。

// The greeter 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;
}

猜你喜欢

转载自blog.csdn.net/weixin_33708432/article/details/86830932