学习brpc:echo服务

2024-04-07 12:44
文章标签 服务 学习 echo brpc

本文主要是介绍学习brpc:echo服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Echo同步客户端

server 端

#include <gflags/gflags.h>
#include <json2pb/pb_to_json.h>
#include <brpc/server.h>
#include "butil/endpoint.h"
#include "echo.pb.h"// flags,用于配置server
DEFINE_bool(echo_attachment, true, "Echo attachment as well");
DEFINE_int32(port, 8000, "TCP Port of this server");
DEFINE_string(listen_addr, "", "Server listen address, may be IPV4/IPV6/UDS."" If this is set, the flag port will be ignored");
DEFINE_int32(idle_timeout_s, -1, "Connection will be closed if there is no ""read/write operations during the last `idle_timeout_s'");class EchoServiceImpl : public example::EchoService {
public:EchoServiceImpl() = default;virtual ~EchoServiceImpl() = default;// response完成后执行的回调static void CallAfterRpc(brpc::Controller* controller, const google::protobuf::Message* req, const google::protobuf::Message* res) {std::string req_str, res_str;// 此时cntl/req/res均没有被析构json2pb::ProtoMessageToJson(*req, &req_str, NULL);json2pb::ProtoMessageToJson(*res, &res_str, NULL);LOG(INFO) << "Got "<< "req:" << req_str<< "and res:" << res_str;
}void Echo (google::protobuf::RpcController* controller,const example::EchoRequest* request,example::EchoResponse* response,google::protobuf::Closure* done) override {brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); // 强转brpc::ClosureGuard done_guard(done); // RAII//日志LOG(INFO) << "Received request[log_id=" << cntl->log_id() << "] from " << cntl->remote_side() << " to " << cntl->local_side()<< ": " << request->message()<< " (attached=" << cntl->request_attachment() << ")";// 生成响应response->set_message("Echo: " + request->message());// 如果有捎带数据,也发送回去if(FLAGS_echo_attachment) {cntl->response_attachment().append(cntl->request_attachment());}// 设置response完成后的回调函数cntl->set_after_rpc_resp_fn(std::bind(EchoServiceImpl::CallAfterRpc,std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));}};int main(int argc, char* argv[]) {// 初始化gflagsGFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);brpc::Server server;EchoServiceImpl service_impl; // 添加服务,,brpc::SERVER_OWNS_SERVICE 表示server是否拥有 service_impl,通常为false    if(server.AddService(&service_impl, brpc::SERVER_OWNS_SERVICE) != 0) {LOG(ERROR) << "Fail to add service";return -1;}// 监听节点, 默认监听所有地址butil::EndPoint point;if(FLAGS_listen_addr.empty()) {point = butil::EndPoint(butil::IP_ANY, FLAGS_port);} else {// 解析监听地址if(butil::str2endpoint(FLAGS_listen_addr.c_str(), &point) != 0) {LOG(ERROR) << "Invalid listen address:" << FLAGS_listen_addr;return -1;}}// 设置配置brpc::ServerOptions options;    options.idle_timeout_sec = FLAGS_idle_timeout_s; // 开启server(异步的)if(server.Start(point, &options) != 0) {LOG(ERROR) << "Fail to start EchoServer";return -1;}// 等待直到退出server.RunUntilAskedToQuit(); return 0;}

client 端

#include <cstdio>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include "echo.pb.h"DEFINE_string(attachment, "attach", "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[]) {GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);// 配置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;// 初始化channelbrpc::Channel channel;if((channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options)) != 0) {LOG(ERROR) << "Fail to initialize channel";return -1;}// channel的封装类,线程间共享example::EchoService_Stub stub(&channel); // 准备请求响应example::EchoRequest request;example::EchoResponse response;brpc::Controller cntl; char buf[128];printf("请输入:");scanf("%s",buf);request.set_message(buf);// 捎带数据cntl.request_attachment().append(FLAGS_attachment);// Cluster 设置为空,表示同步执行,函数会阻塞,直到结果返回,或者超时stub.Echo(&cntl, &request, &response, NULL);if(cntl.Failed()) {LOG(WARNING) << cntl.ErrorText(); // 通常这只是WARNING,为了演示才直接返回return -1;}// 正确输出LOG(INFO) << "Received response from " << cntl.remote_side()<< " to " << cntl.local_side()<< ": " << response.message() << " (attached="<< cntl.response_attachment() << ")"<< " latency=" << cntl.latency_us() << "us";}

Echo 异步客户端

server端代码与同步端端server一致。

client端

#include <cstdio>
#include <gflags/gflags.h>
#include <butil/logging.h>
#include <butil/time.h>
#include <brpc/channel.h>
#include <google/protobuf/stubs/callback.h>
#include "brpc/callback.h"
#include "bthread/bthread.h"
#include "echo.pb.h"DEFINE_string(attachment, "attach", "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");void HandleResponse(brpc::Controller *cntl, example::EchoResponse* response) {// 异步调用需要自己管理cntl 和 response 的生命周期?!// 不应该管理// std::unique_ptr<brpc::Controller> cntl_guard(cntl);// std::unique_ptr<example::EchoResponse> response_guard(response);if(cntl->Failed()) {LOG(ERROR) << "Fail to send EchoRequest, " << cntl->ErrorText();return;}// 故意等一段时间bthread_usleep(10);// 日志LOG(INFO) << "Received response from " << cntl->remote_side()<< ": " << response->message() << " (attached="<< cntl->response_attachment() << ")"<< " latency=" << cntl->latency_us() << "us";}int main(int argc, char* argv[]) {GFLAGS_NS::ParseCommandLineFlags(&argc, &argv, true);// 配置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;// 初始化channelbrpc::Channel channel;if((channel.Init(FLAGS_server.c_str(), FLAGS_load_balancer.c_str(), &options)) != 0) {LOG(ERROR) << "Fail to initialize channel";return -1;}// channel的封装类,线程间共享example::EchoService_Stub stub(&channel); // 准备请求响应example::EchoRequest request;example::EchoResponse response;brpc::Controller cntl; char buf[128];printf("请输入:");scanf("%s",buf);request.set_message(buf);// 捎带数据cntl.request_attachment().append(FLAGS_attachment);// 设置异步回调函数google::protobuf::Closure* done = brpc::NewCallback(&HandleResponse, &cntl, &response);// Cluster 非空,表示异步执行,接收完消息后调用donestub.Echo(&cntl, &request, &response, done);// 继续执行while(true) {bthread_usleep(5);printf("do something\n"); // 可以看到,stub.Echo是立即返回的,不影响后续执行}}

这篇关于学习brpc:echo服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/882628

相关文章

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

TP-Link PDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务

《TP-LinkPDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务》近期,路由器制造巨头普联(TP-Link)在用户群体中引发了一系列重要变动,上个月,公司发出了一则通知,明确要求所... 路由器厂商普联(TP-Link)上个月发布公告要求所有用户必须完成实名认证后才能继续使用普联提供的 D

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

微服务架构之使用RabbitMQ进行异步处理方式

《微服务架构之使用RabbitMQ进行异步处理方式》本文介绍了RabbitMQ的基本概念、异步调用处理逻辑、RabbitMQ的基本使用方法以及在SpringBoot项目中使用RabbitMQ解决高并发... 目录一.什么是RabbitMQ?二.异步调用处理逻辑:三.RabbitMQ的基本使用1.安装2.架构

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

windos server2022的配置故障转移服务的图文教程

《windosserver2022的配置故障转移服务的图文教程》本文主要介绍了windosserver2022的配置故障转移服务的图文教程,以确保服务和应用程序的连续性和可用性,文中通过图文介绍的非... 目录准备环境:步骤故障转移群集是 Windows Server 2022 中提供的一种功能,用于在多个

解决systemctl reload nginx重启Nginx服务报错:Job for nginx.service invalid问题

《解决systemctlreloadnginx重启Nginx服务报错:Jobfornginx.serviceinvalid问题》文章描述了通过`systemctlstatusnginx.se... 目录systemctl reload nginx重启Nginx服务报错:Job for nginx.javas

Python如何实现 HTTP echo 服务器

《Python如何实现HTTPecho服务器》本文介绍了如何使用Python实现一个简单的HTTPecho服务器,该服务器支持GET和POST请求,并返回JSON格式的响应,GET请求返回请求路... 一个用来做测试的简单的 HTTP echo 服务器。from http.server import HT

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用