brpc初步学习

article/2025/8/29 19:56:24

一.BRPC介绍

BRPC百度开源的一个rpc框架,它具有以下特性:

  1. 基于protobuf接口的RPC框架,也提供json等其他数据格式的支持
  2. 囊括baidu内部所有RPC协议,支持多种第三方协议
  3. 模块化设计,层次清晰,很容易添加自定义协议
  4. 全面的服务发现、负载均衡、组合访问支持
  5. 可视化的内置服务和调试工具
  6. 性能上领跑目前其他所有RPC产品

支持的协议
baidu_std(默认)
hulu-pbrpc协议
nova-pbrpc协议
public/pbrpc协议
sofa-pbrpc协议
UB协议
ubrpc协议
HTTP协议
HTTPS协议
凤巢ITP协议
memcache协议
redis协议
mongo协议
hadoop rpc协议

任何使用brpc::Server的进程,都能用HTTP方式直接访问server本身的端口,返回内容为各种内置服务。
通过浏览器直接访问图形界面更加直观;否则用curl方式访问文本格式。

brpc支持一个端口监听多种协议,如可以同时监听baidu_std和http协议发来的请求。

详细文档参见:
https://github.com/brpc/brpc
二.Linux下安装brpc

1. 编译环境安装gcc-4.8.2
(1)先安装gcc-c++.x86_64

yum install gcc-c++.x86_64

(2)编译安装gcc-4.8.2
下载gcc-4.8.2-with-all-requires.tar
指定gcc安装路径 --prefix=/usr/local/gcc4.8.2,在"./configure -enable-threads=posix -disable-checking -disable-mutilib -enable-languages=c,c++ "之后增加一个参数 --prefix=/usr/local/gcc4.8.2
执行 install.sh (执行两遍,第一遍解压,第二遍编译安装,编译时间较长请耐心等待)
(3)更新依赖库
添加 /usr/local/gcc4.8.2/lib、 /usr/local/gcc4.8.2/lib64 至 /etc/ld.so.conf,
在/etc/ld.so.conf文件末尾增加一行 “/usr/local/lib”,保存之后执行ldconfig。
注意每个路径独占一行。执行 ldconfig

ln -sf /usr/local/gcc4.8.2/bin/gcc /usr/bin/gcc
ln -sf /usr/local/gcc4.8.2/bin/g++ /usr/bin/g++

(4)安装 libstdc++
下载 libstdc+±4.8.2-1.x86_64.rpm

rpm -ivh libstdc++-4.8.2-1.x86_64.rpm

2.安装brpc
(1)依赖包安装

yum install libssl-dev realpath libgflags-dev libprotobuf-dev libprotoc-dev \ 
protobuf-compiler  libgtest-dev libleveldb-dev libsnappy-dev \gperf libgoogle-perftools-dev

(2)下载brpc源代码编译安装

git clone https://github.com/brpc/brpc.git
cd ./brpc/
sh config_brpc.sh --headers=/usr/include --libs=/usr/lib --nodebugsymbols
make

(3)把brpc的include和lib文件放到系统目录下,ldconfig下,方便调用。
三. 小示例example:回显程序

提供两个rpc:处理rpc和http格式的请求。

echo.proto文件:

syntax="proto2";
package example;option cc_generic_services = true;message EchoRequest {required string message = 1;
};message EchoResponse {required string message = 1;
};message EchoHttpRequest {};message EchoHttpResponse {};service EchoService {rpc Echo(EchoRequest) returns (EchoResponse);rpc EchoHttp(EchoHttpRequest) returns (EchoHttpResponse);
};

server.cpp

// Copyright (c) 2014 Baidu, Inc.
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.// A server to receive EchoRequest and send back EchoResponse.
#include <iostream>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include "echo.pb.h"using namespace std;DEFINE_bool(echo_attachment, true, "Echo attachment as well");
DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no ""read/write operations during the last `idle_timeout_s'");
DEFINE_int32(logoff_ms, 2000, "Maximum duration of server's LOGOFF state ""(waiting for client to close connection before server stops)");// Your implementation of example::EchoService
// Notice that implementing brpc::Describable grants the ability to put
// additional information in /status.
namespace example {
class EchoServiceImpl : public EchoService {
public:EchoServiceImpl() {};virtual ~EchoServiceImpl() {};virtual void Echo(google::protobuf::RpcController* cntl_base,const EchoRequest* request,EchoResponse* response,google::protobuf::Closure* done) {// This object helps you to call done->Run() in RAII style. If you need// to process the request asynchronously, pass done_guard.release().brpc::ClosureGuard done_guard(done);brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);// The purpose of following logs is to help you to understand// how clients interact with servers more intuitively. You should // remove these logs in performance-sensitive servers.LOG(INFO) << "Received request[log_id=" << cntl->log_id() << "] from " << cntl->remote_side() << " to " << cntl->local_side()<< ": " << request->message()<< " (attached=" << cntl->request_attachment() << ")";// Fill response.response->set_message(request->message());if(cntl->request_protocol() == brpc::PROTOCOL_HTTP) {const brpc::HttpHeader& http_request = cntl->http_request();const std::string& query_data = http_request.uri().query();LOG(INFO) << "Http query data: " << query_data;}// You can compress the response by setting Controller, but be aware// that compression may be costly, evaluate before turning on.// cntl->set_response_compress_type(brpc::COMPRESS_TYPE_GZIP);if (FLAGS_echo_attachment) {// Set attachment which is wired to network directly instead of// being serialized into protobuf messages.cntl->response_attachment().append(cntl->request_attachment());}}virtual void EchoHttp(google::protobuf::RpcController* cntl_base,const EchoHttpRequest* request,EchoHttpResponse* response,google::protobuf::Closure* done) {// This object helps you to call done->Run() in RAII style. If you need// to process the request asynchronously, pass done_guard.release().brpc::ClosureGuard done_guard(done);brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);const brpc::HttpHeader& http_request = cntl->http_request();const std::string& query_data = http_request.uri().query();LOG(INFO) << "Http query data: " << query_data;// You can compress the response by setting Controller, but be aware// that compression may be costly, evaluate before turning on.// cntl->set_response_compress_type(brpc::COMPRESS_TYPE_GZIP);if (FLAGS_echo_attachment) {// Set attachment which is wired to network directly instead of// being serialized into protobuf messages.cntl->response_attachment().append(cntl->request_attachment());}}
};
}  // namespace exampleint main(int argc, char* argv[]) {// Parse gflags. We recommend you to use gflags as well.google::ParseCommandLineFlags(&argc, &argv, true);// Generally you only need one Server.brpc::Server server;// Instance of your service.example::EchoServiceImpl echo_service_impl;// Add the service into server. Notice the second parameter, because the// service is put on stack, we don't want server to delete it, otherwise// use brpc::SERVER_OWNS_SERVICE.if (server.AddService(&echo_service_impl, brpc::SERVER_DOESNT_OWN_SERVICE,"/echo1 => Echo,""/echo2 => EchoHttp") != 0) {LOG(ERROR) << "Fail to add service";return -1;}// Start the server.brpc::ServerOptions options;options.idle_timeout_sec = FLAGS_idle_timeout_s;if (server.Start(FLAGS_port, &options) != 0) {LOG(ERROR) << "Fail to start EchoServer";return -1;}// Wait until Ctrl-C is pressed, then Stop() and Join() the server.server.RunUntilAskedToQuit();cout << "Server Stopped" << endl;return 0;
}

client.cpp

#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include "echo.pb.h"DEFINE_string(attachment, "foo", "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");
DEFINE_string(http_content_type, "application/json", "Content type of http request");int main(int argc, char* argv[]) {// Parse gflags. We recommend you to use gflags as well.google::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 userif (FLAGS_protocol != "http" && FLAGS_protocol != "h2c")  {// Set attachment which is wired to network directly instead of // being serialized into protobuf messages.cntl.request_attachment().append(FLAGS_attachment);} else {cntl.http_request().set_content_type(FLAGS_http_content_type);}// Because `done'(last parameter) is NULL, this function waits until// the response comes back or error occurs(including timedout).stub.Echo(&cntl, &request, &response, NULL);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();}usleep(FLAGS_interval_ms * 1000L);}LOG(INFO) << "EchoClient is going to quit";return 0;
}

本程序用blade构建编译程序,BUILD文件:

cc_binary(name = 'echo_server',srcs = 'server.cpp',deps = [':echo_proto','#brpc','#gflags',]
)cc_binary(name = 'echo_client',srcs = 'client.cpp',deps = [':echo_proto','#brpc','#gflags',]
)proto_library(name = 'echo_proto',srcs = 'echo.proto',
)

运行:
这里写图片描述http请求:curl “http://10.130.134.24:8000/echo2?a=1&b=2” -d ‘{“message”:“hello”}’
该方法是post,如果用get需要设置请求头为:application/proto。

写了个基于brpc框架的小demo,地址是:
brpc demo小程序

四. brpc使用采坑

服务卡死状态健康检查
brpc在服务卡死的状态下(比如死锁),用tcp健康检查,可能无法检查出服务的健康状态。必须用http方式检查,可以检查brpc的web界面。


http://chatgpt.dhexx.cn/article/nqEayfun.shtml

相关文章

brpc介绍、编译与使用

brpc又称为baidu-rpc&#xff0c;是百度开发一款“远程过程调用”网络框架。目前该项目已在github上开源——https://github.com/brpc/brpc。&#xff08;转载请指明出于breaksoftware的csdn博客&#xff09; 据目前公开的资料&#xff0c;我们发现百度内部从2010年开始&#x…

NB-IOT与物联网

1. 物联网的技术格局 短距离(智能家居/穿戴等) --- zigbee, wifi, BLE 长距离 (LPWA 低功耗广域) --- LORA, NB-IOT 关于LORA大致了解了一下情况 . Lora 其实已经是一个很成熟的技术方案. 国外已经大范围使用,国内也有不少公司在基于LORA运营物联网系统. LORA的系统结构…

lora和nbiot的相同点,它们之间有何区别和联系?

在物联网无线数据传输中&#xff0c;有诸多方式可以选择&#xff0c;包括蓝牙、WIFI、FSK、ASK/OOK、Lora、Zigbee、NB-iot、Z-Wave.等&#xff0c; 其中lora 和NBIot 是自2016年来比较热门的两个无线通讯方式。 我们今天就和大家简单的聊聊Lora 和NBiot。 我是在2016年接触…

NB-IOT开发|nbiot开发教程《三》AT指令类模组驱动-STM32实现AT指令状态机

嵌入式开发中我们要时刻保持代码的高效与整洁看之前&#xff0c;先点赞 好习惯&#xff0c;要养成 一、前言 嵌入式开发中我们要时刻保持代码的高效与整洁。在第一节中“NB-IOT开发|nbiot开发教程《一》AT指令类模组驱动解析”我们说到AT指令模组最好的驱动-状态机。本节我们就…

基于华为云IOT平台实现多节点温度采集(STM32+NBIOT)

一、前言 当前的场景是,在高速公路上部署温度采集设备,在高速路地表安装温度检测传感器,检测当前路段的路面实际温度。一段高速路上有多个地点需要采集温度数据。 采集温度数据需要上传到云平台进行数据存储,并且通过可视化界面展示温度变化曲线,支持查询最近几天的温度信…

NB-IoT的优势是什么?

NB-IoT的优势 &#xff1a; • 强链接&#xff1a;在同一基站的情况下&#xff0c;NB-IoT可以比现有无线技术提供50-100倍的接入数。一个扇区能够支持10万个连接&#xff0c;支持低延时敏感度、超低的设备成本、低设备功耗和优化的网络架构。举例来说&#xff0c;受限于带宽&a…

MN316_OPEN(NBIOT)物联网模块环境搭建

因为项目的需要,这里要使用NBIOT,踩了一些坑,这里总结一下! 编译 官方给的SDK如下: 按照说明,在该目录下直接运行如下指令:".\build.bat dlvs_h0 demo"即可成功编译,但是我编译的时候不成功,报错如下: 最后发现是因为我的目录太深的原因造成的,把"MN316_Op…

stm32毕业设计 NBIOT远程通信系统

文章目录 1 简介2 NBIOT 简介2.1 NBIOT 的特点2.2 NBIOT 的优点2.3 NBIOT能做什么 NBIOT 模块使用4 实现效果5 STM32 驱动NBIOT模块6 最后 1 简介 Hi&#xff0c;大家好&#xff0c;NBIOT是近几年不比较火的远程通信模块&#xff0c;是物联网的重要技术&#xff0c;今天学长向…

NB-IoT技术实战开发 ----- NB-IoT介绍

一.1------初识NB-IoT 1、NB-IoT介绍2、 物联网技术发展2.1有线物联网2.2 无线网络网 3、为什么需要NB-IOT4、NB-IOT优势5、NB-IOT解决方案亮点和价值5.1 广覆盖5.2 低功耗5.3低成本5.4 大连接 6、NB-IOT的应用1.智能抄表2.智能停车3.宠物跟踪4.else 1、NB-IoT介绍 NB-----Na…

【物联网】LoRa vs NBIoT

LoRa &#xff08;Long Range&#xff09; VS NB-IoT&#xff08;Narrow Band Internet of Things&#xff09; LoRa和NB&#xff0d;IoT是什么 通常物联网设备分为三类&#xff1a; 无需移动性&#xff0c;大数据量&#xff0c;需较宽频段&#xff1b;移动性强&#xff0…

物联网协议之NBIOT

什么是NBIOT 在物联网行业目前常用的网络通信技术主要有以下这些&#xff1a; nbiot属于一种LTE网络&#xff0c;LTE网络是目前主流的通信网络&#xff0c;覆盖完整、技术成熟&#xff0c;未来大量物联网设备都需要在LTE网络中实现通讯功能。Cat.X这个值是用来衡量用户终端设…

浅谈NBIOT

一、什么是NBIOT&#xff1f; 1、概念 窄带物联网&#xff08;Narrow Band Internet of Things, NB-IoT&#xff09;&#xff0c;NB-IoT构建于蜂窝网络&#xff0c;只消耗大约180KHz的带宽&#xff0c;使用License频段&#xff0c;可采取带内、保护带或独立载波等三种部署方式…

【物联网毕设基础】NBIOT 窄带物联网

文章目录 1 简介2 NBIOT简介3NB的型号介绍3.1 BC95:3.2 BC35&#xff1a;3.3 BC28&#xff1a;3.4 BC26&#xff1a;3.5 BC20&#xff1a;3.6 BC30&#xff1a; 4 NB物联网卡5 OpenCPU6 BC260模块详解6.1 基本性能6.2 引脚介绍6.3 模块供电 7 其他注意点8 最后 1 简介 Hi&…

NB-IoT学习笔记 —— NB-IoT介绍

一、简介 NB-IoT 是指窄带物联网&#xff08;Narrow Band Internet of Things&#xff09;技术&#xff0c;是一种低功耗广域&#xff08;LPWA&#xff09;网络技术标准&#xff0c;基于蜂窝技术&#xff0c;用于连接使用无线蜂窝网络的各种智能传感器和设备&#xff0c;聚焦于…

淘宝客解析url优惠链接获取商品ID

淘宝客解析商品链接获取PID 优惠链接都有一个e参数&#xff0c;提取e参数&#xff0c;直接解析e参数就可以获取推广链接的商品ID&#xff1b; 这是一个优惠推广链接:https://uland.taobao.com/coupon/edetail?ed4tkoUeRofIN%2BoQUE6FNzDiOaI9VHkxMoEVLjjyR2S%2Bki3b8ti%2Bp7j…

ANSI/CAN/UL 1973:2022 固定和运动辅助电源用电池安规要求-最新的英文2022完整版{135页}

ANSI/CAN/UL 1973:2022 Batteries for Use in Stationary andMotive Auxiliary Power Applications 固定和运动辅助电源用电池 UL1973-2022&#xff08;February25,2022&#xff09;.pdf-其它文档类资源-CSDN下载UL1973-2022&#xff08;February25,2022&#xff09;.pdf更多下…

java测试示例-生成ULID

ULID全称Universally Unique Lexicographically Sortable Identifier&#xff0c;直译就是通用唯一按字典排序的标识符&#xff0c;原始仓库是https://github.com/ulid/javascript&#xff0c;由前端开发者alizain发起&#xff0c;基于JavaScript语言。从项目中的commit历史来看…

scrapy_splash简单爬取淘宝页面信息

首先打开淘宝页面&#xff0c;搜索手机&#xff1a; https://uland.taobao.com/sem/tbsearch?refpidmm_26632258_3504122_32538762&clk104511dd93dde330d86022e9ce3a3dc46&keyword手机&page0 # 新建scrapy项目 scrapy startproject taobao # 进入项目目录: cd t…

淘宝API 优惠券查询接口

淘宝API 优惠券查询接口 item_search_coupon - 优惠券查询 返回值说明: 返回数据: Result Object: {“item”: [ {“pic_url”: “https://img.alicdn.com/bao/uploaded/i4/4190751820/O1CN01mohpC11PJbKKu33Gj_!!4190751820.jpg”, “num_iid”: “584401368799”, “se…

UL-1973-2022 储能电池安全标准

UL1973储能电池安全标准 UL-1973版发布于2013年2月15日&#xff0c;&#xff0c;最新更新2022年版。是全球储能电池系统的安全标准&#xff0c;标准主要涵盖给光伏、风能、后备电源、通信基站使用的各类储能电池&#xff0c;并包括对储能系统的结构评估和测试评估。UL1973-2022…