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和异步两种模式,知足不一样场景下的并发需求,本例子里面用的是同步多线程。

相关文章
相关标签/搜索