卿哥聊技术

导航

 

gRPC是Google开源的一款非常棒的系统间通信工具,完美的communication抽象,构建在protobuf之上的RPC.

下面我们聊聊它的应用场景,grpc为分布式系统而生,可以是系统间通信,也可以是系统内部进程间通信。下面以python为例。

笔者系统里装有python2.7和python3,下面就用python2.7举例:

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 command

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

posted on 2018-01-20 10:26  卿哥聊技术  阅读(394)  评论(0编辑  收藏  举报