用grpc_cb代替grpc++

用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;
    });

服务器实现

  1. 先实现服务类

    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().

  2. 开启服务

    Server svr;
    svr.AddListeningPort("0.0.0.0:50051");
    RouteGuideImpl service(db_path);
    svr.RegisterService(service);
    svr.BlockingRun();
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值