gRPC Golang/Python使用

gRPC Golang/Python使用

之前開發網站都是用http協議,學過TCP/IP協議的人都知道,在傳輸層TCP的基礎上,應用層HTTP就是填充了必定規則的文本.html

1.gRPC使用和介紹

工做中使用到gRPC,其實http請求也是一種rpc變種,遠程進程調用.gRPC底層是HTTP2協議java

gRPC一開始由google開發,是一款語言中立、平臺中立、開源的遠程過程調用(RPC)系統,面向移動和HTTP/2設計。目前提供C、Java和Go語言版本,分別是:grpc,grpc-java,grpc-go.其中C版本支持C,C++,Node.js,Python,Ruby,Objective-C,PHP和C#支持.python

gRPC基於HTTP/2標準設計,帶來諸如雙向流、流控、頭部壓縮、單TCP鏈接上的多複用請求等特。這些特性使得其在移動設備上表現更好,更省電和節省空間佔用。git

gRPC基於如下理念:定義一個服務,指定其可以被遠程調用的方法(包含參數和返回類型)。在服務端實現這個接口,並運行一個gRPC服務器來處理客戶端調用。在客戶端擁有一個存根可以像服務端同樣的方法,即調用彷彿就在同一臺機器。github

能夠使用不一樣語言平臺進行開發golang

grpc.png

gRPC 默認使用protocol buffers來進行消息通信,這是Google開源的一套成熟的結構數據序列化機制api

參考: gRPC 官方文檔中文版 | 概念bash

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/protobufcurl

安裝參考: 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

相關文章
相關標籤/搜索