0
点赞
收藏
分享

微信扫一扫

用grpc_cb代替grpc++


用grpc_cb代替grpc++


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

  1. 开启服务

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


举报

相关推荐

GRPC

grpc

gRPC

Linux(gRPC):Ubuntu22.04安装gRPC

what is grpc

grpc protobuf

0 条评论