C++实现grpc异步服务器

首先可以跑一下grpc官方的例子,网址:
https://grpc.io/docs/languages/cpp/quickstart/

一、下载grpc包并编译

https://github.com/grpc/grpc
在编译grpc之前需要下载protobuf、abseil、re2、zlib等,放到grpc的相关目录下,
然后可以写个脚本编译grpc库,如下:

#!/bin/bash
grpcdir="${pwd}"

cd grpc/camke
mkdir build && cd build

cmake -LH -DCMAKE_INSTALL_PREFIX=$grpcdir/ver ../..
make -j4 && make install

编译之后grpc相关的lib库都已经编好在ver/lib或者lib64下,并且在bin目录下会生成protoc和grpc_cpp_plugin,供后续编译protobuf文件使用。

二、定义protobuf文件,并进行编译

1、定义rsp的Result.proto

syntax = "proto3";

import "google/protobuf/any.proto";
option java_package = "com.aaa.proto.base";
option java_outer_classname="ResultProto";
package base;

message Result {
    int32 code = 1;
    string msg = 2;
    google.protobuf.Any data = 3;
}

2、定义Req服务的 helloworld.proto

syntax = "proto3";

import "Result.proto";
option java_package = "com.aaa.service";
option java_outer_classname = "ServiceProto";
package service;

//服务器接口
service ServiceInterface {
    // 服务接口1
    rpc Service1 (Req1) returns (base.Result) { }
    // 服务接口2
    rpc Service2 (Req2) returns (base.Result) { }
}

//====================== 服务接口1 ========================//

message Req1 {
    string str = 1;  
    int32  k= 2;  
}

message Rsp1 {
    repeated Struct struct = 1;  // 信息列表
}

message Struct {
    string str = 1; 
    int32    i = 2;
    bool     b = 3; 
}

//====================== 服务接口2 ========================//
message Req2 {
    string str = 1;  
    int32  k= 2;  
}

message Rsp2 {
    repeated Struct struct = 1;  // 信息列表
}


定义好proto文件后将文件编译:
1、protoc -I --cpp_out=./ /protodir/*.proto  

该命令会生成 helloworld.pb.h 和 helloworld.pb.cc, Result.pb.h 和 Result.pb.cc文件,主要是有关消息类的声明和实现,

2、protoc --grpc_out=./ --plugin=protoc-gen-grpc=/bin/grpc_cpp_plugin /protodir/*.proto  

该命令会生成 helloworld.grpc.pb.h 和 helloworld.grpc.pb.cc, Result.grpc.pb.h 和 Result.grpc.pb.cc文件,主要是服务类相关的声明和实现,在.proto文件里面定义的service会自动生成一个同名的c++类,
该类会嵌套一个Stub的类,Stub类中会有对应service下的rpc接口的实现,该实例中对应的rpc接口是search,并且service同名类中 有一个NewStub的接口,
该接口会调用Stub类并返回一个Stub的对象即存根。


将生成的.pb.h和.pb.cc文件加入自己的工程中,使用Protobuf库提供的API来编写应用程序。

三、服务端程序

头文件 AsyncServer.h:

#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <mutex>

#include "grpcpp/grpcpp.h"

#include "helloworld.grpc.pb.h"
#include "Result.grpc.pb.h"

using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerCompletionQueue;
using grpc::ServerContext;
using grpc::Status;
//using helloworld::Greeter;
//using helloworld::HelloReply;
//using helloworld::
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值