于此止?头像
rpc的认识和简单的rpc的api封面图

rpc的认识和简单的rpc的api

介绍

在这里插入图片描述

RPC(Remote Procedure Call)远程过程调用,简单来说就是客户端在不知道调用细节的情况下,调用远程计算机上的某个功能就像调用本地功能一样(应用于我们当地的算力不足,而我们的远程服务器的算例多的情况),其主要目标就是让构建分布式计算(应用)更容易,在提供强大的远程调用能力时不损失本地调用的语义简洁性。

我们的rpc是依赖我们的protobuf这个库的,
这个库的相关情况请查看:[[protobuf]]

框架开发者语言支持序列化http协议文档编译问题(ubuntu22.04)服务端推送异步调用流式传输易用性
grpcgoogleC++、Java、Python、Gopb支持较完善,无中文文档submodule下载依赖vpn不支持1.异步客户端需自建消费线程,使用麻烦
2.支持异步服务端
支持(接口易用)1.简单易用
2.跨语言、跨平台
brpcbaiduC++pb支持较完善,有中文文档基本无问题支持,效果一般,依靠长RPC实现1.回调方式实现客户端异步调用支持(弱原生)1.API简洁,上手友好
2.基于sofa-pbrpc封装,自带资源管理
srpcsogouC++pb、Thrift支持内容简单,托管于github,无独立站点基本无问题不支持1.支持异步客户端
2.依托workflow实现异步服务端
不支持异步向,性能高,上手复杂度偏高
sofa-pbrpcbaiduC++、Javapb支持官方文档偏少依赖库版本老旧,编译易出问题不支持1.回调方式支持客户端异步调用不支持1.轻量化
2.接口简洁,上手容易

brpc是用c++语言编写的工业级RPC框架,常用于搜索、存储、机器学习、广告、推荐等高性能系统。 你可以使用它:

  • 搭建能在一个端口支持多协议的服务,或访问各种服务
    • restful http/https, h2/gRPC。使用brpc的http实现比libcurl方便多了。从其他语言通过HTTP/h2+json访问基于protobuf的协议.

    • redis和memcached, 线程安全,比官方client更方便。

    • rtmp/flv/hls,可用于搭建流媒体服务.

    • 支持thrift,线程安全,比官方client更方便

    • 各种百度内使用的协议: baidu_std, streaming_rpc, hulu_pbrpc, sofa_pbrpc, nova_pbrpc, public_pbrpc, ubrpc和使用nshead的各种协议.

    • 基于工业级的RAFT算法实现搭建高可用分布式系统,已在braft开源。

  • Server能同步或异步处理请求。
  • Client支持同步、异步、半同步,或使用组合channels(管道)简化复杂的分库或并发访问。
  • 通过http界面调试服务,使用cpu, heap, contention profilers.
  • 获得更好的延时和吞吐.
  • 把你组织中使用的协议快速地加入brpc,或定制各类组件,包括命名服务(dns, zk, etcd),负载均衡(rr, random, consistent hashing)

安装

先安装依赖,我们的rpc是基于我们的protobuf的进行的。

dev@dev-host:~/workspace$ sudo apt-get install -y git g++ libssl-dev libprotobuf-dev libprotoc-dev protobuf-compiler libleveldb-dev

安装brpc

dev@dev-host:~/workspace$ git clone [https://github.com/apache/brpc.git](https://github.com/apache/brpc.git)
dev@dev-host:~/workspace$ cd brpc/
dev@dev-host:~/workspace/brpc$ mkdir build && cd build
dev@dev-host:~/workspace/brpc/build$ cmake -DCMAKE_INSTALL_PREFIX=/usr .. && cmake --build . -j6
dev@dev-host:~/workspace/brpc/build$ make && sudo make install

类与接口介绍

日志输出类与接口

包含头文件:

#include <butil/logging.h>

brpc库内有人家自己的日志输出模块(无法替换,除非修改库内源码中所有的日志输出操作后重新编译库进行安装),这里我们主要是了解他的日志级别,将不需要的日志输出给禁用掉,避免其运行时的大量日志输出影响我们的视线。

namespace logging {
enum LoggingDestination {
    LOG_TO_NONE             = 0, //默认日志的接收端,不写文件和debug日志系统。日志在最后一步进行丢失
    LOG_TO_FILE             = 1 << 0,   //向我们的指定的文件进行书写
    LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,   //写我们的stderr/输出我们的DEBUG的字符串

    LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,

    // On Windows, use a file next to the exe; on POSIX platforms, where
    // it may not even be possible to locate the executable on disk, use
    // stderr.
#if defined(OS_WIN)
    LOG_DEFAULT = LOG_TO_FILE,
#elif defined(OS_POSIX)
    LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
#endif
};
//日志相关的字段
struct BUTIL_EXPORT LoggingSettings {
    LoggingSettings();
    LoggingDestination logging_dest; //日志选择哪种类型
};
bool InitLogging(const LoggingSettings& settings); //初始化我们的日志
}

protobuf的原生接口

//===================================behin=========================================
//=====================我们的异步操作我们用来直接调用我们的自定义方法=====================
namespace google {
namespace protobuf {
class PROTOBUF_EXPORT Closure {
 public:
    Closure() {}
    virtual ~Closure();
    virtual void Run() = 0; //调用这个参数时、告诉我们的服务器我们的上面参数调用完了。
};

inline Closure* NewCallback(void (*function)());

//这是我们的protobuf内部的实现,我们的rpc重写了这一个对应的接口
class PROTOBUF_EXPORT RpcController {
    bool Failed();
    std::string ErrorText();
}
}
}


class PROTOBUF_EXPORT Service {
 public:
  inline Service() {}
  virtual ~Service();

  // When constructing a stub, you may pass STUB_OWNS_CHANNEL as the second
  // parameter to the constructor to tell it to delete its RpcChannel when
  // destroyed.
  enum ChannelOwnership { STUB_OWNS_CHANNEL, STUB_DOESNT_OWN_CHANNEL };

  // Get the ServiceDescriptor describing this service and its methods.
  virtual const ServiceDescriptor* GetDescriptor() = 0;

  // Call a method of the service specified by MethodDescriptor.  This is
  // normally implemented as a simple switch() that calls the standard
  // definitions of the service's methods.
  //
  // Preconditions:
  // * method->service() == GetDescriptor()
  // * request and response are of the exact same classes as the objects
  //   returned by GetRequestPrototype(method) and
  //   GetResponsePrototype(method).
  // * After the call has started, the request must not be modified and the
  //   response must not be accessed at all until "done" is called.
  // * "controller" is of the correct type for the RPC implementation being
  //   used by this Service.  For stubs, the "correct type" depends on the
  //   RpcChannel which the stub is using.  Server-side Service
  //   implementations are expected to accept whatever type of RpcController
  //   the server-side RPC implementation uses.
  //
  // Postconditions:
  // * "done" will be called when the method is complete.  This may be
  //   before CallMethod() returns or it may be at some point in the future.
  // * If the RPC succeeded, "response" contains the response returned by
  //   the server.
  // * If the RPC failed, "response"'s contents are undefined.  The
  //   RpcController can be queried to determine if an error occurred and
  //   possibly to get more information about the error.
  virtual void CallMethod(const MethodDescriptor* method,
                          RpcController* controller, const Message* request,
                          Message* response, Closure* done) = 0;

  // CallMethod() requires that the request and response passed in are of a
  // particular subclass of Message.  GetRequestPrototype() and
  // GetResponsePrototype() get the default instances of these required types.
  // You can then call Message::New() on these instances to construct mutable
  // objects which you can then pass to CallMethod().
  //
  // Example:
  //   const MethodDescriptor* method =
  //     service->GetDescriptor()->FindMethodByName("Foo");
  //   Message* request  = stub->GetRequestPrototype (method)->New();
  //   Message* response = stub->GetResponsePrototype(method)->New();
  //   request->ParseFromString(input);
  //   service->CallMethod(method, *request, response, callback);
  virtual const Message& GetRequestPrototype(
      const MethodDescriptor* method) const = 0;
  virtual const Message& GetResponsePrototype(
      const MethodDescriptor* method) const = 0;

 private:
  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Service);
};

//===============================描述信息===========================================
class PROTOBUF_EXPORT MethodDescriptor {
 public:
  typedef MethodDescriptorProto Proto;

  // Name of this method, not including containing scope.
  const std::string& name() const;
  // The fully-qualified name of the method, scope delimited by periods.
  const std::string& full_name() const;
  // Index within the service's Descriptor.
  int index() const;

  // The .proto file in which this method was defined.  Never nullptr.
  const FileDescriptor* file() const;
  // Gets the service to which this method belongs.  Never nullptr.
  const ServiceDescriptor* service() const;

  // Gets the type of protocol message which this method accepts as input.
  const Descriptor* input_type() const;
  // Gets the type of protocol message which this message produces as output.
  const Descriptor* output_type() const;

  // Gets whether the client streams multiple requests.
  bool client_streaming() const;
  // Gets whether the server streams multiple responses.
  bool server_streaming() const;

  // Get options for this method.  These are specified in the .proto file by
  // placing lines like "option foo = 1234;" in curly-braces after a method
  // declaration.  Allowed options are defined by MethodOptions in
  // descriptor.proto, and any available extensions of that message.
  const MethodOptions& options() const;

  // See Descriptor::CopyTo().
  void CopyTo(MethodDescriptorProto* proto) const;

  // See Descriptor::DebugString().
  std::string DebugString() const;

  // See Descriptor::DebugStringWithOptions().
  std::string DebugStringWithOptions(const DebugStringOptions& options) const;

  // Source Location ---------------------------------------------------

  // Updates |*out_location| to the source location of the complete
  // extent of this method declaration.  Returns false and leaves
  // |*out_location| unchanged iff location information was not available.
  bool GetSourceLocation(SourceLocation* out_location) const;
};
//================================end==============================================

服务端类与接口

这里只介绍主要用到的成员与接口。

namespace brpc {
struct ServerOptions {
    //无数据传输,则指定时间后关闭连接
    int idle_timeout_sec; // Default: -1 (disabled) 设置我们的定时器
    int num_threads; // 线程工作的数量 pthread worker 数量,默认值是CPU 核数 + 1
    //....
}

enum ServiceOwnership {
    //添加服务失败时,服务器将负责删除服务对象
    SERVER_OWNS_SERVICE,
    //添加服务失败时,服务器也不会删除服务对象,让我们进行手动的删除
    SERVER_DOESNT_OWN_SERVICE
};

class Server {
	//增加我们的服务
    int AddService(google::protobuf::Service* service,
                   ServiceOwnership ownership);
    //启动我们的服务
    int Start(int port, const ServerOptions* opt);
    //终止我们的服务器
    int Stop(int closewait_ms/*not used anymore*/);
    //等待我们的服务器
    int Join();
    //休眠直到ctrl+c按下,或者stop和join服务器
    void RunUntilAskedToQuit();
}

//=========================对我们的异步调度进行RAII风格的重写==========================
//语义是“告诉 brpc:我处理完了,可以回包了”。你调用 `done->Run()` 那一刻,brpc 才开始序列化 `response`、发送回包、回收 `Controller`、更新 bvar。因此它是整个生命周期中唯一由你触发的关键步骤。
class ClosureGuard {
    explicit ClosureGuard(google::protobuf::Closure* done);
    ~ClosureGuard() { if (_done) _done->Run(); }
}
}

api的介绍

AddService 增加我们的服务
  • service: 类型:google::protobuf::Service* 是我们的protobuf中进行创建的对应的服务类型。
    这个就是我们写了对应的服务接口的类型我们的原类型为:
class CalcService : public ::PROTOBUF_NAMESPACE_ID::Service {
#define PROTOBUF_NAMESPACE_ID google::protobuf
所以我们这里时做了我们的切割,让我们对应的参数可以直接的进行我们传递。
  • ownership:类型: ServiceOwnership 我们的服务器执行后我们要怎么处理对象。
  • 返回值成功返回0,失败返回-1.
Start 启动我们的服务器
  • port: 类型int 设置我们的端口号
  • opt: 类型:ServerOptions 设置我们的服务的基本操作
  • 返回值: 同上
Stop 结束我们的服务器

closewait_ms:类型int 无实际意义,我们的这个参数原本是进行等待现有连接和请求结束的最长毫秒数但是这个没有具体的实现。

HTTP相关类

//======================================beghin=====================================
//===================================设置我们的uri==================================
class URI {
typedef butil::FlatMap<std::string, std::string> QueryMap;
typedef QueryMap::const_iterator QueryIterator;
//设置http的uri路径
int SetHttpURL(const std::string& url); // Returns 0 on success, -1 otherwise
void set_path(const std::string& path)//设置路径
void set_host(const std::string& host)//设置ip
void set_port(int port)//设置端口
void SetHostAndPort(const std::string& host_and_optional_port); //设置ip和端口
//删除对应的QueryIterator结构
size_t RemoveQuery(const char* key); // Returns 1 on removed, 0 otherwise

//获取ip
const std::string& host() const { return _host; }
//获取端口
int port()
const std::string& path() //获取路径
const std::string& user_info()
const std::string& query() const;  
const std::string* GetQuery(const std::string& key)
void SetQuery(const std::string& key, const std::string& value);
QueryIterator QueryBegin()
QueryIterator QueryEnd()
size_t QueryCount()
};


//==================================http的请求方法==================================
enum HttpMethod {
    HTTP_METHOD_DELETE    = 0,
    HTTP_METHOD_GET       = 1,
    HTTP_METHOD_HEAD      = 2,
    HTTP_METHOD_POST      = 3,
    HTTP_METHOD_PUT       = 4,
};
const char *HttpMethod2Str(HttpMethod http_method); //我们的请求方法转换器,将我们的枚举类型转化为对应的字符型
bool Str2HttpMethod(const char* method_str, HttpMethod* method);


//===================================http的状态码===================================
static const int HTTP_STATUS_OK = 200;
static const int HTTP_STATUS_BAD_REQUEST = 400;
static const int HTTP_STATUS_UNAUTHORIZED = 401;
static const int HTTP_STATUS_FORBIDDEN = 403;
static const int HTTP_STATUS_NOT_FOUND = 404;
static const int HTTP_STATUS_METHOD_NOT_ALLOWED = 405;
static const int HTTP_STATUS_INTERNAL_SERVER_ERROR = 500;

//==================================http的头部信息==================================
class HttpHeader{
const std::string& content_type() //获取我们的内容类型
void set_content_type(const std::string& type) //设置我们的内容类型
void SetHeader(const std::string& key, const std::string& value) //设置我们的请求头
const std::string* GetHeader(const std::string& key) //获取我们的请求头 
URI& uri() { return _uri; } //获取我们内部的uri字段,有设置路径的api,我们可以进行调用设置
const URI& uri() const { return _uri; }   //获取我们的uri路径
HttpMethod method() const { return _method; } //获取我们的请求方法
void set_method(const HttpMethod method) //设置我来们的请求方法
int status_code() //获取我们的状态码
void set_status_code(int status_code) //设置我们的状态码
}


//=================================rpc的HTTP操作字段================================
//我们感觉protobuf结构太单一进行继承我们的对应方法
class Controller : public google::protobuf::RpcController {
    void set_timeout_ms(int64_t timeout_ms); //设置我们的定时器
    void set_max_retry(int max_retry); //设置我们的最大内核数
    void Reset();
    google::protobuf::Message* response();//我们发送的消息进行对应操作
    HttpHeader& http_response();//获取我们http的响应字段
    butil::IOBuf& response_attachment();//响应正文
    HttpHeader& http_request();//获取我们http的请求字段
    butil::IOBuf& request_attachment();//请求正文

    bool Failed(); //是否错误
    std::string ErrorText(); //错误信息
    using AfterRpcRespFn = std::function<
        void(Controller* cntl,
             const google::protobuf::Message* req,
             const google::protobuf::Message* res)>;
    void set_after_rpc_resp_fn(AfterRpcRespFn&& fn)
};
//==============================HTTP请求的正文部分的操作==============================
namespace butil {
//我们的butil内部设置的一些对应的缓冲区的操作
class IOBuf {
size_t pop_front(size_t n); //删掉前n个字节,返回值实际取出的字节数
size_t pop_back(size_t n);//删掉后n个字节,返回值返回实际取出的字节数
bool cut1(void* c);//截取一个字节给void *c 返回值成功返回true,失败返回false
// Returns 0 on success, -1 otherwise.
int copy_to(std::string *s); //拷贝对应的数据
// Convert all data in this buffer to a std::string
std::string to_string() const; //获取我们所有的数据转化为字符串
void clear(); //清除我们的正文信息
bool empty() const; //判断我们正文是否为空
size_t length() const; //计算我们正文的长度
//追加对应的字符串
void append(const IOBuf& other); //追加一个IOBUF
int push_back(char c); //追加一个字符
int append(void const* data, size_t count); //追加一个void const* 追加大小为count
int append(char const* s); //追加一个const char* 字符串
int append(const std::string& s); //追加一个字符串
};
}


//======================google::protobuf RpcController============================
class PROTOBUF_EXPORT RpcController {
 public:
  inline RpcController() {}
  virtual ~RpcController();

  // Client-side methods ---------------------------------------------
  // These calls may be made from the client side only.  Their results
  // are undefined on the server side (may crash).

  // Resets the RpcController to its initial state so that it may be reused in
  // a new call.  Must not be called while an RPC is in progress.
  virtual void Reset() = 0;

  // After a call has finished, returns true if the call failed.  The possible
  // reasons for failure depend on the RPC implementation.  Failed() must not
  // be called before a call has finished.  If Failed() returns true, the
  // contents of the response message are undefined.
  virtual bool Failed() const = 0;

  // If Failed() is true, returns a human-readable description of the error.
  virtual std::string ErrorText() const = 0;

  // Advises the RPC system that the caller desires that the RPC call be
  // canceled.  The RPC system may cancel it immediately, may wait awhile and
  // then cancel it, or may not even cancel the call at all.  If the call is
  // canceled, the "done" callback will still be called and the RpcController
  // will indicate that the call failed at that time.
  virtual void StartCancel() = 0;

  // Server-side methods ---------------------------------------------
  // These calls may be made from the server side only.  Their results
  // are undefined on the client side (may crash).

  // Causes Failed() to return true on the client side.  "reason" will be
  // incorporated into the message returned by ErrorText().  If you find
  // you need to return machine-readable information about failures, you
  // should incorporate it into your response protocol buffer and should
  // NOT call SetFailed().
  virtual void SetFailed(const std::string& reason) = 0;

  // If true, indicates that the client canceled the RPC, so the server may
  // as well give up on replying to it.  The server should still call the
  // final "done" callback.
  virtual bool IsCanceled() const = 0;

  // Asks that the given callback be called when the RPC is canceled.  The
  // callback will always be called exactly once.  If the RPC completes without
  // being canceled, the callback will be called after completion.  If the RPC
  // has already been canceled when NotifyOnCancel() is called, the callback
  // will be called immediately.
  //
  // NotifyOnCancel() must be called no more than once per request.
  virtual void NotifyOnCancel(Closure* callback) = 0;

 private:
  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RpcController);
};
//=======================================end=======================================

参数解析

  1. Controller类:在我们的brpc搭建我们的http服务器和客户端中,请求以及处理都是通过我们的brpc::Contorller来完成的。
    • 参数的解析:
    • HttpHeader& http_response();
      • 对于客户端来说,用于获取我们的响应头部信息。
      • 对于服务端来说,用于设置我们的响应头部信息。
    • HttpHeader& http_request();
      • 对于客户端来说,用于设置我们的请求头部信息。
      • 对于服务端来说,用于获取我们的请求头部信息。
    • butil::IOBuf& response_attachment();
      • 对于客户端来说,用于获取我们响应的正文信息。
      • 对于服务端来说,用于设置我们响应的正文信息。
    • butil::IOBuf& request_attachment();
      • 对于客户端来说,用于设置我们的请求正文信息。
      • 对于服务端来说,用于获取我们的请求正文信息。

客户端类与接口:

//======================================beghin=====================================
namespace brpc {
//===============================序列化协议类型======================================
enum ProtocolType : int {
    PROTOCOL_UNKNOWN = 0,
    PROTOCOL_BAIDU_STD = 1,   //百度的标准类型
    PROTOCOL_STREAMING_RPC = 2,
    PROTOCOL_HULU_PBRPC = 3,
    PROTOCOL_SOFA_PBRPC = 4,
    PROTOCOL_RTMP = 5,
    PROTOCOL_THRIFT = 6,
    PROTOCOL_HTTP = 7,   //http协议
    PROTOCOL_PUBLIC_PBRPC = 8,
    PROTOCOL_NOVA_PBRPC = 9,
    PROTOCOL_REDIS = 10,
    PROTOCOL_NSHEAD_CLIENT = 11,
    PROTOCOL_NSHEAD = 12,
    PROTOCOL_HADOOP_RPC = 13,
    PROTOCOL_HADOOP_SERVER_RPC = 14,
    PROTOCOL_MONGO = 15,
    PROTOCOL_UBRPC_COMPACK = 16,
    PROTOCOL_DIDX_CLIENT = 17,
    PROTOCOL_MEMCACHE = 18,
    PROTOCOL_ITP = 19,
    PROTOCOL_NSHEAD_MCPACK = 20,
    PROTOCOL_DISP_IDL = 21,
    PROTOCOL_ERSDA_CLIENT = 22,
    PROTOCOL_UBRPC_MCPACK2 = 23,
    PROTOCOL_CDS_AGENT = 24,
    PROTOCOL_ESP = 25,
    PROTOCOL_H2 = 26
};


//============================序列化协议的类型=======================================
class AdaptiveProtocolType {
public:
    explicit AdaptiveProtocolType() : _type(PROTOCOL_UNKNOWN) {}
    explicit AdaptiveProtocolType(ProtocolType type) : _type(type) {}
    explicit AdaptiveProtocolType(butil::StringPiece name) { *this = name; }
    ~AdaptiveProtocolType() {}

    void operator=(ProtocolType type) {
        _type = type;
        _name.clear();
        _param.clear();
    }

    void operator=(butil::StringPiece name) {
        butil::StringPiece param;
        const size_t pos = name.find(':');
        if (pos != butil::StringPiece::npos) {
            param = name.substr(pos + 1);
            name.remove_suffix(name.size() - pos);
        }
        _type = StringToProtocolType(name);
        if (_type == PROTOCOL_UNKNOWN) {
            _name.assign(name.data(), name.size());
        } else {
            _name.clear();
        }
        if (!param.empty()) {
            _param.assign(param.data(), param.size());
        } else {
            _param.clear();
        }
    };

    operator ProtocolType() const { return _type; }

    const char* name() const {
        return _name.empty() ? ProtocolTypeToString(_type) : _name.c_str();
    }

    bool has_param() const { return !_param.empty(); }
    const std::string& param() const { return _param; }

private:
    ProtocolType _type;
    std::string _name;
    std::string _param;
};


//===============================客户端的配置参数====================================
//使用包含头文件 #include <brpc/channel.h>
struct ChannelOptions {
    //请求连接超时时间
    int32_t connect_timeout_ms;// Default: 200 (milliseconds)
    //rpc请求超时时间
    int32_t timeout_ms;// Default: 500 (milliseconds)
    //最大重试次数
    int max_retry;// Default: 3
    //序列化协议类型  options.protocol = "baidu_std"; 
    AdaptiveProtocolType protocol; //我们一般将他设置为我们的baidu_std百度的标准化协议
    //....
}
//================================客户端rpc/信道的搭建===============================
class Channel : public ChannelBase {
    //初始化接口,成功返回0;
    int Init(
        const char* server_addr_and_port, //192.168.xx.xx:9000
        const ChannelOptions* options);
    // 做的就是一次完整的 RPC 调用:把你选中的方法(`method`)连同 `request` 一起发给 `Init` 时配置的那台服务器,等响应回来后把结果填进 `response`(同步调用直接返回、异步时通过 `done` 回调通知你)
    
void CallMethod(const google::protobuf::MethodDescriptor* method,//protobuf的原生
        google::protobuf::RpcController* controller,//Http类有继承对应的关系
        const google::protobuf::Message* request,
        google::protobuf::Message* response,
        google::protobuf::Closure* done);
};
//继承体系
class Channel : public ChannelBase {
class ChannelBase : public google::protobuf::RpcChannel/*non-copyable*/,
public Describable {

//==========我们的rpc客户端支持我们的异步处理,我们在进行异步的时候要调用这个函数============
inline ::google::protobuf::Closure* NewCallback(void (*function)());
// See Closure.
inline ::google::protobuf::Closure* NewCallback(void (*function)()) {
  return new internal::FunctionClosure0(function, true);
}

// See Closure.
inline ::google::protobuf::Closure* NewPermanentCallback(void (*function)()) {
  return new internal::FunctionClosure0(function, false);
}

// See Closure.
template <typename Class, typename Pointer>
inline ::google::protobuf::Closure* NewCallback(const Pointer& object, void (Class::*method)()) {
  return new internal::MethodClosure0<Class, Pointer>(object, method, true);
}
//...

//======================protobuf生成的客户端对应的rpc类===============================
class CalcService_Stub : public CalcService {
 public:
  // 我的这个是一路继承下来的,所以我的这个参数可以直接传递我们的Channel
  CalcService_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel);
  CalcService_Stub(::PROTOBUF_NAMESPACE_ID::RpcChannel* channel,
                   ::PROTOBUF_NAMESPACE_ID::Service::ChannelOwnership ownership);
  ~CalcService_Stub();

  inline ::PROTOBUF_NAMESPACE_ID::RpcChannel* channel() { return channel_; }

  // implements CalcService ------------------------------------------

  //我们主要的是使用这个函数
  void Add(::PROTOBUF_NAMESPACE_ID::RpcController* controller,
                       const ::calc::Requset* request,
                       ::calc::Response* response,
                       ::google::protobuf::Closure* done);
 private:
  ::PROTOBUF_NAMESPACE_ID::RpcChannel* channel_;
  bool owns_channel_;
  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CalcService_Stub);
  
  
//=================================Closure=========================================
	class PROTOBUF_EXPORT Closure {
	 public:
	  Closure() {}
	  virtual ~Closure();
	
	  virtual void Run() = 0;
	
	 private:
	  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure);
	};  
};
//=====================================end=========================================

api接口的解析

  1. Init

    • 参数:
    • server_addr_and_port 我们的ip地址,点分十进制
    • options 我们的客户端的相关参数
  2. CallMethod

    • 参数:
    • method: 要选择哪个方法,由.proto生成的还是其他
    • contorller:控制这次调用: 超时错误信息
    • request:请求参数
    • response:响应参数
    • done:异步回调
  3. Add : 我们的这个add和我们的服务端的add不一样,我们的这个add不要进行重写

    • 参数:
    • controller 我们对应HTTP的相关参数
    • request 我们的请求参数
    • response 我们的响应参数
    • done 两种情况
      • 情况1: 我们传递null,则表示我们的本次请求时我们的同步请求(阻塞)
      • 情况2: 我们可以进行实例化我们的done对象,进行设置回调函数进行异步非阻塞调用(Add调用后立即返回,等到拿到结果会自动调用设置的回调函数进行响应处理)

定时任务相关

头文件:bthread/unstable.h,butil/time.h
// Return 0 on success, errno otherwise.
int bthread_timer_add(bthread_timer_t* id,
    struct timespec abstime,
    void (*on_timer)(void*),
    void* arg);

// Returns: 0 - exist & not-run;
//          1 - still running;
//          EINVAL - not exist.
int bthread_timer_del(bthread_timer_t id);

namespace butil {
timespec microseconds_from_now(int64_t millisseconds);
timespec seconds_from_now(int64_t seconds);
}

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/buhuizhiyuci/article/details/171292139

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--