Skip to content

Commit

Permalink
BugFix: fix the problem of uneven traffic using backup request in IP …
Browse files Browse the repository at this point in the history
…direct connection scenario
  • Loading branch information
chhy2009 committed Jan 30, 2024
1 parent 99fc614 commit 3a9a394
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
1 change: 1 addition & 0 deletions trpc/naming/common/util/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ cc_library(
hdrs = ["utils_help.h"],
deps = [
"//trpc/naming/common:common_defs",
"//trpc/util/algorithm:random",
],
)
38 changes: 29 additions & 9 deletions trpc/naming/common/util/utils_help.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,44 @@

#include <stdlib.h>

#include "trpc/util/algorithm/random.h"

namespace trpc {

int SelectMultiple(const std::vector<TrpcEndpointInfo>& src, std::vector<TrpcEndpointInfo>* dst,
const int select_size) {
if (src.empty()) {
return -1;
}

int need_select_size = select_size;
int instances_size = src.size();
if (need_select_size > instances_size) {
need_select_size = instances_size;
}
int pos = rand() % instances_size;
if (pos + need_select_size > instances_size) {
// Add instances_size-pos elements
dst->assign(src.begin() + pos, src.end());
// Add need_select_size - (instances_size-pos) elements
int reserve_size = need_select_size - (instances_size - pos);
dst->insert(dst->end(), src.begin(), src.begin() + reserve_size);
} else {
dst->assign(src.begin() + pos, src.begin() + pos + need_select_size);
dst->reserve(need_select_size);

int pos = trpc::Random<uint32_t>() % instances_size;
dst->push_back(src[pos]);
if (instances_size == 1) {
return 0;
}

// Randomly obtain the offset of the next node to be retrieved and retrieve 'need_select_size - 1' nodes
// continuously (skipping the selected node).
int pos_offset = trpc::Random<uint32_t>() % (instances_size - 1) + 1;
int next_pos = pos + pos_offset;
for (int i = 1; i < need_select_size; i++) {
if (next_pos >= instances_size) {
next_pos -= instances_size;
}
if (next_pos == pos) {
next_pos++;
}
if (next_pos >= instances_size) {
next_pos -= instances_size;
}
dst->push_back(src[next_pos++]);
}

return 0;
Expand Down

0 comments on commit 3a9a394

Please sign in to comment.