gRPC實戰

gRPC是Google開源的一款很是棒的系統間通訊工具,完美的communication抽象,構建在protobuf之上的RPC.python

下面咱們聊聊它的應用場景,grpc爲分佈式系統而生,能夠是系統間通訊,也能夠是系統內部進程間通訊。下面以python爲例。json

筆者系統裏裝有python2.7和python3,下面就用python2.7舉例:restful

sudo python2.7 install grpcio-tools多線程

sudo pip2.7 install grpcio併發

1. create calculator.proto框架

syntax = "proto3";

message Number {
    float value = 1;          
}

service Calculator {
    rpc SquareRoot(Number) returns (Number) {}
}

2. execute following commandpython2.7

/usr/bin/python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. calculator.proto

3. create calculator.py異步

import math

def square_root(x):
    y = math.sqrt(x)
    return y

4. create server.py分佈式

#!/usr/bin/python

import grpc
from concurrent import futures
import time

import calculator_pb2
import calculator_pb2_grpc

import calculator

class CalculatorService(calculator_pb2_grpc.CalculatorService):
    def SquareRoot(self, request, response):
        response = calculator_pb2.Number()
        response.value = calculator.square_root(request.value)
        return response

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

calculator_pb2_grpc.add_CalculatorService_to_server(CalculatorService(), server)

print "Starting server. Listening on port 5566"
server.add_insecure_port('[::]:5566')
server.start()

try:
    while True:
        time.sleep(80000)
except KeyboardInterrupt:
    server.stop(0)

5.  create client.py工具

#!/usr/bin/python

import grpc

import calculator_pb2
import calculator_pb2_grpc

channel = grpc.insecure_channel('localhost:5566')

stub = calculator_pb2_grpc.CalculatorStub(channel)

number = calculator_pb2.Number(value=64)

response = stub.SquareRoot(number)

print response.value

Run:

./server.py

Starting server. Listening on port 5566

 

./client.py

8.0

 

grpc 同時還支持grpc gateway, 提供一個gateway做爲reverse proxy, 目前好像只支持go,至關於提供一個HTTP restful endpoint, 而後可以返回json,這樣HTTP client也能夠使用grpc + gateway的解決方案。總之google這套開源框架仍是很是使人滿意的。

另外想說說它同時支持thread pool和異步兩種模式,知足不一樣場景下的併發需求,本例子裏面用的是同步多線程。

相關文章
相關標籤/搜索