class ModifyRequest : public brpc::CallMapper {
public:
brpc::SubCall Map(int channel_index /*starting from 0*/, const google::protobuf::MethodDescriptor* method, const google::protobuf::Message* request, google::protobuf::Message* response) {
brpc::RedisRequest* copied_req = new brpc::RedisRequest;
LOG_WARNING("index: %d, key:%s", channel_index, ((const BrsBroadcastMultiRequest*)request)->keys(channel_index).c_str());
copied_req->AddCommand(((const BrsBroadcastMultiRequest*)request)->keys(channel_index).c_str());
// 拷贝并修改request,最后的flag告诉pchan在RPC结束后删除Request和Response。
brpc::RedisResponse* resp = new brpc::RedisResponse;
// return brpc::SubCall(method, request, response->New(), brpc::DELETE_RESPONSE);
return brpc::SubCall(method, copied_req, resp, brpc::DELETE_REQUEST | brpc::DELETE_RESPONSE);
}
};
class RedisResponseMerger : public brpc::ResponseMerger {
public:
virtual brpc::ResponseMerger::Result Merge(google::protobuf::Message* response, const google::protobuf::Message* sub_response) {
const brpc::RedisResponse* sub_resp = (const brpc::RedisResponse*)sub_response;
Brs_get_uid_Response* resp = (Brs_get_uid_Response*)response;
if (sub_resp->reply(0).is_error() || sub_resp->reply(0).type() != brpc::REDIS_REPLY_ARRAY) {
LOG_WARNING("redis failed[%s]", sub_resp->reply(0).error_message());
return brpc::ResponseMerger::FAIL;
}
for (unsigned int index = 0; index < sub_resp->reply(0).size(); index++) {
if (sub_resp->reply(0)[index].size() <= 0) {
continue;
}
resp->add_uids(strtoull(sub_resp->reply(0)[index].c_str(), NULL, 10));
}
return brpc::ResponseMerger::MERGED;
}
};
brpc::ParallelChannelOptions pchan_options;
pchan_options.timeout_ms = 500;
if (channel.Init(&pchan_options) != 0) {
LOG(ERROR) << "Fail to init ParallelChannel";
return -1;
}
brpc::ChannelOptions sub_options;
sub_options.protocol = "redis";
sub_options.connection_type = "pooled";
sub_options.max_retry = 2;
brpc::Channel* sub_channel = new brpc::Channel;
// Initialize the channel, NULL means using default options.
// options, see `brpc/channel.h'.
if (sub_channel->Init("list://127.0.0.1:17379", "rr", &sub_options) != 0) {
LOG(ERROR) << "Fail to initialize sub_channel";
return -1;
}
brpc::CallMapper* call_mapper = new ModifyRequest;
brpc::ResponseMerger* merger = new RedisResponseMerger;
for (int i = 0; i < g_conf.group_cnt; ++i) {
if (channel.AddChannel(sub_channel, brpc::OWNS_CHANNEL, call_mapper, merger) != 0) {
LOG(ERROR) << "Fail to AddChannel, i=" << i;
return -1;
}
}
c++-brpc ParallelChannel 实战
最新推荐文章于 2023-11-30 21:42:33 发布