IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    用grpc_cb代替grpc++

    金庆发表于 2017-01-22 10:06:00
    love 0

    用grpc_cb代替grpc++

    (金庆的专栏 2017.1)

    jinq0123/grpc_cb
    是 Google gRpc 的C++库。
    它依赖于 grpc, 采用回调接口,简化了使用,用来代替 grpc++ 库。

    使用简介如下。

    定义服务

    用 proto 文件定义服务:

     

    // See examples/protos/route_guide.proto.

    syntax = "proto3";

    package routeguide;

    // Interface exported by the server.
    service RouteGuide {
      // A simple RPC.
      rpc GetFeature(Point) returns (Feature) {}
    }

    message Point {
      int32 latitude = 1;
      int32 longitude = 2;
    }

    message Feature {
      string name = 1;
      Point location = 2;
    }
    生成服务器和客户端代码

     

    详见:examples/protos/generate.bat

            protoc.exe -I . --cpp_out=../cpp_cb/route_guide route_guide.proto
            protoc.exe -I . --grpc_out=../cpp_cb/route_guide --plugin=protoc-gen-grpc=grpc_cpp_cb_plugin.exe route_guide.proto
    在examples/cpp_cb/route_guide/ 生成以下文件:
    • route_guide.pb.h, 消息类定义
    • route_guide.pb.cc, 消息类实现
    • route_guide.grpc_cb.pb.h, 服务类定义
    • route_guide.grpc_cb.pb.cc, 服务类实现

    生成的命名空间RouteGuide将包含

    • 客户端使用的Stub类.
    • 需服务器实现的Service类.

    客户端调用RPC

    同步调用

    ChannelSptr channel(new Channel("localhost:50051"));
    Stub stub(channel);

    Point point = MakePoint(0, 0);
    Feature feature;
    Status status = stub.BlockingGetFeature(point, &feature);

    异步调用

    stub.AsyncGetFeature(point,
    [](const Feature& feature) {
    cout << feature.name() << endl;
    });

    服务器实现

    先实现服务类

        class RouteGuideImpl final : public routeguide::RouteGuide::Service {
        public:
            void GetFeature(const Point& point,
                    const GetFeature_Replier& replier) override {
                Feature feature;
                feature.set_name("...");
                replier.Reply(feature);
            }    
        }
    GetFeature()不必立即应答,可复制保存replier后直接返回, 待应答内容准备完成后,再调用Reply().

    开启服务
        Server svr;
        svr.AddListeningPort("0.0.0.0:50051");
        RouteGuideImpl service(db_path);
        svr.RegisterService(service);
        svr.BlockingRun();


    金庆 2017-01-22 18:06 发表评论


沪ICP备19023445号-2号
友情链接