• gRPC实战


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

  • 相关阅读:
    [Javascript] twitterbootstrap: 解决2.1版本中modal加载远程内容时,只加载一次的问题
    向大型网站学习SEO优化之道
    [Yii Framework] 使用Yii Framework开发微信公众平台
    [jQuery] ajax跨域处理方式
    [jQuery] form提交到iframe之后,获取iframe里面内容
    [Ubuntu] fatal: recursion detected in die handler
    [Yii Framework] Yii如何实现前后台的session分离
    [ubuntu] ubuntu13.04 64bit,安装FastDFS4.06过程遇到的问题和解决方案
    [转] 怎样在Ubuntu上安装Git服务器
    [ubuntu] ubuntu13.04切换桌面/工作区的方法
  • 原文地址:https://www.cnblogs.com/huashao1985/p/8320014.html
Copyright © 2020-2023  润新知