grpc rest
Google最近发布了gRPC作为开放源代码 ,它是使用多种编程语言的远程过程调用(RPC)的有效框架。
RPC是服务器之间的一种常用通信方法,并不是什么新鲜事物。 它们的历史可以追溯到1980年代,并且由于它们具有服务器端的性质,通常对于大多数计算机用户,甚至对于大多数软件开发人员,都不会接触到它们。 鉴于RPC的作用是支持计算机服务器之间的通信,因此它们大多数对于系统管理员和DevOps都是可见的。 也就是说,它们的重要性至关重要,因为它们是连接承载大量Internet流量的许多分布式系统的标准机制。
![Wikipedia服务器的图像 Image of Wikipedia servers](https://i-blog.csdnimg.cn/blog_migrate/b269ae0740fb87c8c3e4f55b5f6b2b47.png)
Wikipedia服务器的图像
gRPC基于最近完成的HTTP / 2标准,该标准支持以下新功能 :
- 双向流
- 流量控制
- 标头压缩
- 通过单个TCP连接复用请求
gRPC提供了多种语言的库,包括:
- C
- C ++
- Java
- 走
- Node.js
- Python
- Ruby
gRPC的源代码可以在GitHub上找到 ,其中包括大量的文档和一个主要的网页 。 gRPC的发布与协议缓冲区的新版本proto3同步。 协议缓冲区用于:
- 指定服务器之间交换的消息的内容和结构
- 序列化和反序列化消息
- 为读写消息的多种语言的对象生成源代码
- 提供一种对消息定义进行版本控制的机制,以便具有不同版本的客户端和服务器仍可以互操作
给我看gRPC
快速入门指南汇总了Python中的Hello World 。 它定义了一个您(客户)向其发送名称的服务,即“ John Doe”,并且该服务以以下组成的字符串答复:“ Hello,John Doe”。
以下是将通过网络传递的消息:
// The request message containing the user's name.
message HelloRequest { optional string name = 1; }
// The response message containing the greetings.
message HelloReply { optional string message = 1; }
这是服务定义:
syntax = "proto2";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
如果我们将此服务和消息定义放在文件helloworld.proto中,并使用Proto3编译器对其进行处理,它将为客户端和服务器端生成Python代码。
客户端看起来像:
import helloworld_pb2
_TIMEOUT_SECONDS = 10
def run():
with helloworld_pb2.early_adopter_create_Greeter_stub('localhost', 50051) as stub:
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), _TIMEOUT_SECONDS)
print "Greeter client received: " + response.message
if __name__ == '__main__':
run()
服务器端将如下所示:
import time
import helloworld_pb2
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2.EarlyAdopterGreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
def serve():
server = helloworld_pb2.early_adopter_create_Greeter_server(Greeter(), 50051, None, None)
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop()
if __name__ == '__main__':
serve()
入门指南中提供了更多详细信息。
免责声明:上面的Python代码中的缩进不正确。 有关正确正确的Python语法,请点击提供的链接。
翻译自: https://opensource.com/bus/15/3/google-grpc-open-source-remote-procedure-calls
grpc rest