Skip to content

Commit

Permalink
Merge pull request #3354 from jsonwan/github_perf/execute
Browse files Browse the repository at this point in the history
perf: 选择任意一个容器执行时使用随机算法 #3352
  • Loading branch information
jsonwan authored Dec 25, 2024
2 parents 923d943 + c2eafe1 commit 78c3185
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,35 @@

package com.tencent.bk.job.common.util;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
* 随机工具类
*/
public class RandomUtil {

private static final Random random = new Random();

/**
* 生成随机的正整数,可用于多线程环境
*
* @return 随机数
*/
public static long getRandomPositiveLong() {
long value = random.nextLong();
long value = ThreadLocalRandom.current().nextLong();
if (value == Long.MIN_VALUE || value == 1L) {
return 1;
} else if (value < 0) {
return -value;
}
return value;
}

/**
* 生成[0,bound)范围内的随机正整数,可用于多线程环境
*
* @param bound 边界值,不包含
* @return 随机数
*/
public static int nextInt(int bound) {
return ThreadLocalRandom.current().nextInt(bound);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.tencent.bk.job.common.util;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;

public class RandomUtilTest {

@Test
void testNextInt() {
for (int i = 0; i < 100; i++) {
int bound = RandomUtil.nextInt(1000) + 1;
assertThat(RandomUtil.nextInt(bound)).isGreaterThanOrEqualTo(0);
assertThat(RandomUtil.nextInt(bound)).isLessThan(bound);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import com.tencent.bk.job.common.model.dto.HostDTO;
import com.tencent.bk.job.common.model.dto.ResourceScope;
import com.tencent.bk.job.common.service.AppScopeMappingService;
import com.tencent.bk.job.common.util.RandomUtil;
import com.tencent.bk.job.execute.model.KubeClusterFilter;
import com.tencent.bk.job.execute.model.KubeContainerFilter;
import com.tencent.bk.job.execute.model.KubeContainerPropFilter;
Expand Down Expand Up @@ -180,7 +181,9 @@ public List<Container> listContainerByContainerFilter(long appId, KubeContainerF
fillNodeHostInfo(appId, containers);

if (filter.isFetchAnyOneContainer()) {
return Collections.singletonList(containers.get(0));
// 随机选择一个容器
int index = RandomUtil.nextInt(containers.size());
return Collections.singletonList(containers.get(index));
} else {
return containers;
}
Expand Down

0 comments on commit 78c3185

Please sign in to comment.