架构与系统设计 / 系统课时
优先级与权重路由
优先级与权重路由
本课实现一套可落地的通道路由器:先用优先级确定候选组,再按权重随机分配流量,并通过固定随机种子验证 70% 与 30% 的比例控制结果。
学习目标
- 理解优先级筛选与权重随机各自解决的问题
- 编写可运行的 Java 路由实现
- 验证流量比例并处理无可用通道等边界
路由规则如何组合
优先级负责“先选哪一组”,权重负责“组内如何分流”。约定数值越小优先级越高,只要优先级为 1 的通道仍有可用成员,就不会把请求发送到优先级为 2 的备用组。
同一优先级内,通道命中概率为 $P_i = w_i / (w_1 + ... + w_n)$。权重不必相加等于 100,例如 7 和 3、70 和 30 的比例完全相同。

实现优先级与权重选择
下面的程序先筛出最高优先级组,再使用累计权重区间完成随机选择。示例固定随机种子,因此每次运行都能得到相同结果,便于自动化测试;生产环境可以改用 ThreadLocalRandom。
java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class PriorityWeightRouterDemo {
record Channel(String code, int priority, int weight, boolean enabled) {}
static final class Router {
private final Random random;
Router(long seed) {
this.random = new Random(seed);
}
Channel route(List<Channel> channels) {
int bestPriority = channels.stream()
.filter(Channel::enabled)
.mapToInt(Channel::priority)
.min()
.orElseThrow(() -> new IllegalStateException("没有可用通道"));
List<Channel> candidates = channels.stream()
.filter(Channel::enabled)
.filter(channel -> channel.priority() == bestPriority)
.toList();
int totalWeight = candidates.stream()
.mapToInt(Channel::weight)
.sum();
int hit = random.nextInt(totalWeight) + 1;
int cursor = 0;
for (Channel channel : candidates) {
cursor += channel.weight();
if (hit <= cursor) {
return channel;
}
}
throw new IllegalStateException("权重计算异常");
}
}
public static void main(String[] args) {
List<Channel> channels = new ArrayList<>();
channels.add(new Channel("channel-a", 1, 70, true));
channels.add(new Channel("channel-b", 1, 30, true));
channels.add(new Channel("channel-c", 2, 100, true));
Router router = new Router(20260803L);
Map<String, Integer> counts = new LinkedHashMap<>();
for (int i = 0; i < 10_000; i++) {
Channel selected = router.route(channels);
counts.merge(selected.code(), 1, Integer::sum);
}
counts.forEach((code, count) ->
System.out.printf("%s=%d%n", code, count));
System.out.println(
"channel-c=0(高优先级组可用时不会进入低优先级组)");
}
}预期输出:
text
channel-a=7042
channel-b=2958
channel-c=0(高优先级组可用时不会进入低优先级组)结果不是简单轮询,而是让大量请求逐步逼近 70% 与 30% 的目标比例。单次请求无法保证比例,验证时应使用足够大的样本量。
处理关键边界
路由配置入库或加载时,应拒绝负权重,并保证候选组总权重大于 0。权重为 0 的通道可以保留配置,但不会获得流量;所有通道禁用时必须返回明确错误,不能静默选择备用值。
生产环境还应先按支付方式、币种、金额、地区等条件得到候选集,再应用本课策略。优先级和权重只负责排序与分流,不能替代业务规则过滤。
验收路由结果
验收时至少检查三点:高优先级组可用时低优先级组命中数为 0;关闭高优先级组后备用组能够接管;在一万次以上请求中,各通道占比与配置比例接近,且不存在未配置通道。
按自己的节奏,确认真正理解。