最近換了新的項(xiàng)目,接觸到了新的技術(shù)grpc蔫巩,本著熱愛&不學(xué)習(xí)就會(huì)落后的精神谆棱,自己閑來(lái)也照葫蘆畫瓢了搞個(gè)demo。
一批幌、grpc概念
先看看官方的文檔:
gRPC 一開始由 google 開發(fā)础锐,是一款語(yǔ)言中立、平臺(tái)中立荧缘、開源的遠(yuǎn)程過(guò)程調(diào)用(RPC)系統(tǒng)皆警。gRPC 是一個(gè)高性能、開源和通用的 RPC 框架截粗,面向移動(dòng)和 HTTP/2 設(shè)計(jì)信姓。目前提供 C、Java 和 Go 語(yǔ)言版本绸罗,分別是:grpc, grpc-java意推,grpc-go. 其中 C 版本支持 C, C++, Node.js,Python珊蟀, Ruby, Objective-C, PHP和 C# 支持.
gRPC 基于 HTTP/2 標(biāo)準(zhǔn)設(shè)計(jì)菊值,帶來(lái)諸如雙向流、流控育灸、頭部壓縮腻窒、單 TCP 連接上的多復(fù)用請(qǐng)求等特。這些特性使得其在移動(dòng)設(shè)備上表現(xiàn)更好磅崭,更省電和節(jié)省空間占用儿子。
二、grpc環(huán)境準(zhǔn)備
1砸喻、本次demo使用python版本柔逼,首先需要準(zhǔn)備python3環(huán)境:
Python 3.5或更高版本
pip 版本9.0.1或更高
2、安裝grpc
pip install grpcio
3割岛、安裝 ProtoBuf 相關(guān)的 python 依賴庫(kù)
pip install protobuf
4愉适、安裝 python grpc 的 protobuf 編譯工具:
pip install grpcio-tools
三、開始demo項(xiàng)目
1癣漆、創(chuàng)建一個(gè)空的項(xiàng)目
2儡毕、項(xiàng)目下新建一個(gè)proto文件夾
3、新建helloworld.proto文件,內(nèi)容如下:
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
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;
}
4腰湾、執(zhí)行命令
切換到上一步的目錄雷恃,執(zhí)行
python -m grpc_tools.protoc -I./ --python_out=. --grpc_python_out=. helloworld.proto
5、創(chuàng)建服務(wù)端和客戶端代碼
#coding=utf-8
from concurrent import futures
import time
import grpc
from proto import helloworld_pb2
from proto import helloworld_pb2_grpc
_ONE_DAY_IN_SECONDS = 60 * 60 * 24
class Greeter(helloworld_pb2_grpc.GreeterServicer):
# 工作函數(shù)
def SayHello(self, request, context):
print(request.name)
message = "This message is from Server.And what i want to say is hello \" " + request.name + " \"";
return helloworld_pb2.HelloReply(message = message)
def serve():
# gRPC 服務(wù)器
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
server.add_insecure_port('[::]:50051')
print("sever is opening ,waiting for message...")
server.start() # start() 不會(huì)阻塞费坊,如果運(yùn)行時(shí)你的代碼沒(méi)有其它的事情可做倒槐,你可能需要循環(huán)等待。
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except KeyboardInterrupt:
server.stop(0)
if __name__ == '__main__':
serve()
#coding=utf-8
from __future__ import print_function
import grpc
from proto import helloworld_pb2
from proto import helloworld_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='Hello World附井! This is message from client!'))
print("Greeter client received: " + response.message)
if __name__ == '__main__':
run()
6讨越、運(yùn)行起來(lái)測(cè)試
成功了!