Skip to main content

conreg_client/lb/
weight_random.rs

1use crate::Instance;
2use crate::lb::{LoadBalance, LoadBalanceError};
3
4#[derive(Debug, Default)]
5pub struct WeightRandomLoadBalance {}
6
7impl WeightRandomLoadBalance {
8    pub fn new() -> Self {
9        Self::default()
10    }
11}
12
13impl LoadBalance for WeightRandomLoadBalance {
14    async fn get_instance(&self, service_id: &str) -> Result<Instance, LoadBalanceError> {
15        let instances = self.instances(service_id).await?;
16
17        if instances.is_empty() {
18            return Err(LoadBalanceError::NoAvailableInstance(
19                service_id.to_string(),
20            ));
21        }
22        if instances.len() == 1 {
23            return Ok(instances[0].clone());
24        }
25
26        // 计算总权重
27        let total_weight: u64 = instances.iter().map(|instance| instance.get_weight()).sum();
28
29        // 生成0到总权重之间的随机数
30        let random_weight: u64 = fastrand::u64(0..total_weight);
31
32        // 根据随机数和权重选择实例
33        let mut current_weight = 0;
34        for instance in &instances {
35            let weight = instance.get_weight();
36            current_weight += weight;
37            if random_weight < current_weight {
38                return Ok(instance.clone());
39            }
40        }
41
42        // 理论上不会执行到这里
43        Ok(instances[0].clone())
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use crate::init;
51    #[tokio::test]
52    async fn test_random_weight_load_balance() {
53        let _ = init().await;
54        let lb = WeightRandomLoadBalance::default();
55        let instances = lb
56            .get_instance("conreg_client-ecdb9f5551f4f00c")
57            .await
58            .unwrap();
59        println!("instances: {:?}", instances);
60    }
61}