brpc中同步、异步、半同步和取消操作

本文详细介绍了brpc框架中同步、异步、半同步RPC调用的实现和注意事项,包括同步调用的原地等待特性、异步调用的回调函数机制、半同步调用的等待机制以及如何取消RPC调用。通过代码示例和运行结果展示了各种调用方式的特点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接如题,从brpc开源的文档中看到brpc既支持同步调用,同时也支持异步调用。这里直接给出同步、异步的例子,同时对其进行分析。

1、brpc同步调用

brcp的同步调用是之前的echo的简单例子,所谓同步就是client对远端的server进行调用,同时自己原地等待,等待rpc返回之后,在进行之后的操作。
代码如下:

#include <iostream>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include "echo.pb.h"

using namespace std;

DEFINE_string(attachment, "", "Carry this along with requests");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, "0.0.0.0:8000", "IP Address of server");
DEFINE_string(load_balancer, "", "The algorithm for load balancing");
DEFINE_int32(timeout_ms, 100, "RPC timeout in milliseconds");
DEFINE_int32(max_retry, 3, "Max retries(not including the first RPC)"); 
DEFINE_int32(interval_ms, 1000, "Milliseconds between consecutive requests");

int main(int argc, char* argv[]) {
   
   
    // Parse gflags. We recommend you to use gflags as well.
    GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);
    
    // A Channel represents a communication line to a Server. Notice that 
    // Channel is thread-safe and can be shared by all threads in your program.
    brpc::Channel channel;
    
    // Initialize the channel, NULL means using default options.
    brpc::ChannelOptions options;
    options.protocol = FLAGS_protocol;
    options.connection_type = FLAGS_connection_type;
    options.timeout_ms = FLAGS_timeout_ms/*milliseconds*/;
    options.max_retry = FLAGS_max_retry;
    if (channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options) != 0) {
   
   
        LOG(ERROR) << "Fail to initialize channel";
        return -1;
    }

    // Normally, you should not call a Channel directly, but instead construct
    // a stub Service wrapping it. stub can be shared by all threads as well.
    example::EchoService_Stub stub(&channel);

    // Send a request and wait for the response every 1 second.
    int log_id = 0;
    while (!brpc::IsAskedToQuit()) {
   
   
        // We will receive response synchronously, safe to put variables
        // on stack.
        example::EchoRequest request;
        example::EchoResponse response;
        brpc::Controller cntl;

        request.set_message("hello world");

        cntl.set_log_id(log_id ++);  // set by user
        // Set attachment which is wired to network directly instead of 
        // being serialized into protobuf messages.
        cntl.request_attachment().append(FLAGS_attachment);

        // Because `done'(last parameter) is NULL, this function waits until
        // the response comes back or error occurs(including timedout).
        
        //注意这里是同步调用,因为回调函数done被设置为NULL
        //同步表示stub调用rpc,返回之后才会进行后面的语句
        stub.Echo(&cntl, &request, &response, NULL);
        cout << "after stub_method 0 " << endl;
        if (!cntl.Failed()) {
   
   
            LOG(INFO) << "Received response from " << cntl.remote_side()
                << " to " << cntl.local_side()
                << ": " << response.message() << " (attached="
                << cntl.response_attachment() << ")"
                << " latency=" << cntl.latency_us() << "us";
        } else {
   
   
            LOG(WARNING) << cntl.ErrorText();
        }
        cout << "after stub_method 1 " << endl;
        usleep(FLAGS_interval_ms * 1000L);
    }
	
    LOG(INFO) << "EchoClient is going to quit";
    return 0;
}
注意

1、stub.Echo调用可以看到回调函数被设置为NULL,那么此时调用被设置为同步操作,原地等待。

2、同步访问中的response/controller不会在CallMethod后被框架使用,它们都可以分配在栈上。注意,如果request/response字段特别多字节数特别大的话,还是更适合分配在堆上。

运行结果

同步进行,按照操作流程一步步打印
在这里插入图片描述

2、brpc异步调用

brpc的异步调用指的是和同步调用相比,在进行rpc调用之后,此时callmethod就结束了,进行继续执行后续的动作,等到rpc返回之后,会调用事先注册的回调函数,回调函数进行后面rpc返回之后的操作。
代码如下:

#include <iostream>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include "echo.pb.h"

using namespace std;

DEFINE_bool(send_attachment, true, "Carry attachment along with requests");
DEFINE_string(protocol, "baidu_std", "Protocol type. Defined in src/brpc/options.proto");
DEFINE_string(connection_type, "", "Connection type. Available values: single, pooled, short");
DEFINE_string(server, <
<think>好的,我现在要帮用户介绍一下brpc的HTTP客户端。首先,我需要确认自己对brpc的了解是否正确。brpc是百度开源的RPC框架,常用于构建高性能的分布式服务。它的HTTP客户端应该支持基本的请求方法,比如GET、POST,还有连接池、超时设置等功能。 用户可能想知道如何使用brpc的HTTP客户端,或者它的主要特点是什么。可能还需要比较它其他HTTP客户端库的区别,比如libcurl或者requests(Python)。不过用户明确问的是介绍,所以应该涵盖基本概念、核心功能、使用步骤示例代码。 接下来,我需要回忆brpc中HTTP客户端的相关类API。例如,brpc::Channel是用来与服务端通信的主要类,可能需要配置为HTTP协议。然后,使用brpc::Controller来控制每次请求的参数响应处理。 要注意用户提到的系统级指令,比如行内数学表达式要用$...$,不过在这个问题中可能用不上数学公式。但需要确保所有的技术术语、代码片段正确使用格式。例如,类名方法名用反引号,代码块用三个反引号包围,并标明语言。 用户要求结构清晰,分步骤说明,所以应该分点介绍,比如核心功能、使用步骤、示例代码、注意事项等。还要用中文,避免专业术语过多,必要时解释概念。 需要检查是否有错误,比如是否正确处理HTTP请求的步骤,示例代码是否正确。例如,创建Channel时,协议是否设置为brpc::PROTOCOL_HTTP,是否正确使用HttpHeader设置请求头,发送请求的方法是否正确调用。 可能还需要提到一些高级功能,比如重试机制、连接池配置、超时设置,以及如何处理响应,比如解析JSON或处理cookies。不过用户可能只需要基础介绍,所以保持简洁,但覆盖关键点。 最后,确保回答真实可靠,参考官方文档或可靠的资料,避免猜测不确定的功能。如果有不确定的地方,可能需要查阅brpc的文档或示例代码,但根据已有的知识进行回答。</think>brpc的HTTP客户端是brpc框架中用于发送HTTP请求的核心组件,具有高性能易用性特点。以下从核心功能到使用方式的分步解析: 一、核心功能特性 1. **多协议支持**:基于`brpc::Channel`可同时支持HTTP/1.1、HTTP/2协议 2. **连接复用**:内置连接池(默认长连接),自动管理连接生命周期 3. **超时控制**:支持连接超时、请求超时等多级超时设置(例如:通过`Controller.set_timeout_ms()`) 4. **异步调用**:提供同步半同步、全异步三种调用模式 5. **负载均衡**:支持随机、轮询等多种负载均衡策略 二、基础使用步骤 1. **创建Channel**: ```cpp brpc::ChannelOptions options; options.protocol = brpc::PROTOCOL_HTTP; // 设置协议类型 brpc::Channel channel; if (channel.Init("http://www.example.com", "", &options) != 0) { // 处理初始化失败 } ``` 2. **构造请求**: ```cpp brpc::Controller cntl; cntl.http_request().uri() = "/api/v1/data"; // 设置请求路径 cntl.http_request().set_method(brpc::HTTP_METHOD_POST); // 设置请求方法 cntl.request_attachment().append("{"key":"value"}"); // 添加请求体 ``` 3. **设置请求头**: ```cpp cntl.http_request().SetHeader("Content-Type", "application/json"); cntl.http_request().SetHeader("Authorization", "Bearer token"); ``` 4. **发起调用**: ```cpp channel.CallMethod(nullptr, &cntl, nullptr, nullptr, nullptr); ``` 5. **处理响应**: ```cpp if (!cntl.Failed()) { const brpc::HttpResponse& res = cntl.response(); LOG(INFO) << "Status: " << res.status_code(); LOG(INFO) << "Body: " << cntl.response_attachment(); } else { LOG(ERROR) << "Error: " << cntl.ErrorText(); } ``` 三、高级功能示例 1. **设置超时**: ```cpp cntl.set_timeout_ms(3000); // 设置3秒超时 ``` 2. **异步调用**: ```cpp void* callback_param = ...; // 自定义回调参数 google::protobuf::Closure* done = brpc::NewCallback(&HandleResponse, &cntl, callback_param); channel.CallMethod(nullptr, &cntl, nullptr, nullptr, done); ``` 四、性能优化建议 1. **复用Channel对象**:避免重复创建带来的开销 2. **合理设置连接数**:通过`options.connection_type`调整连接池大小 3. **启用压缩**:设置`cntl.set_request_compress_type(brpc::COMPRESS_TYPE_GZIP)` 五、常见问题处理 1. **DNS缓存**:默认启用,可通过`ChannelOptions`调整 2. **重定向处理**:默认不自动跟随,需手动处理3xx响应 3. **SSL配置**:通过`options.mutable_ssl_options()`设置证书 建议结合官方文档(https://github.com/apache/brpc)中的http_client示例进行实践验证,通过`bvar`监控模块可实时观察客户端性能指标。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值