gRPC Golang/Python使用

gRPC Golang/Python使用

以前开发网站都是用http协议,学过TCP/IP协议的人都知道,在传输层TCP的基础上,应用层HTTP就是填充了一定规则的文本.

1.gRPC使用和介绍

工作中使用到gRPC,其实http请求也是一种rpc变种,远程进程调用.gRPC底层是HTTP2协议

gRPC一开始由google开发,是一款语言中立、平台中立、开源的远程过程调用(RPC)系统,面向移动和HTTP/2设计。目前提供C、Java和Go语言版本,分别是:grpc,grpc-java,grpc-go.其中C版本支持C,C++,Node.js,Python,Ruby,Objective-C,PHP和C#支持.

gRPC基于HTTP/2标准设计,带来诸如双向流、流控、头部压缩、单TCP连接上的多复用请求等特。这些特性使得其在移动设备上表现更好,更省电和节省空间占用。

gRPC基于以下理念:定义一个服务,指定其能够被远程调用的方法(包含参数和返回类型)。在服务端实现这个接口,并运行一个gRPC服务器来处理客户端调用。在客户端拥有一个存根能够像服务端一样的方法,即调用仿佛就在同一台机器。

可以使用不同语言平台进行开发

grpc.png

gRPC 默认使用protocol buffers来进行消息通讯,这是Google开源的一套成熟的结构数据序列化机制

参考: gRPC 官方文档中文版 | 概念

Protocol

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.

项目地址:https://github.com/google/protobuf

安装参考: https://github.com/google/protobuf/blob/master/src/README.md

安装The protocol compiler

sudo apt-get install autoconf automake libtool curl make g++ unzip
./autogen.sh
####
#执行./autogen.sh时,报error: configure.ac:1: file'gtest/m4/acx_pthread.m4' does not exist的错误。
#在gmock目录新建gtest文件夹,拷贝项目根目录下m4文件夹至gtest文件夹
####
./configure
make
make check
sudo make install
sudo ldconfig # refresh shared library cache.

使用(下面go语言还需安装插件)

go get -u github.com/golang/protobuf/proto
go get -u github.com/golang/protobuf/protoc-gen-go

文档参考: protocol-buffers文档

Go gRPC

Go版库:https://github.com/grpc/grpc-go

获取:

go get google.golang.org/grpc

使用

protoc --go_out=plugins=grpc:. *.proto

如果要网关转http,请

go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger

然后

#!/usr/bin/env bash
protoc -I/usr/local/include -I. \
  -I$GOPATH/src \
  -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  --go_out=plugins=grpc:. \
  msg_newest.proto

protoc -I/usr/local/include -I. \
  -I$GOPATH/src \
  -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis \
  --grpc-gateway_out=logtostderr=true:. \
  msg_newest.proto

Python gRPC

pip install grpcio==1.4.0
pip install grpcio-tools==1.4.0
pip install protobuf

python -m grpc.tools.protoc --python_out=pbdata --grpc_python_out=pbdata -I . msg.proto

转载请注明:http://www.lenggirl.com/cap/grpc.html

猜你喜欢

转载自www.cnblogs.com/nima/p/11750938.html