Skip to main content

conreg_client/lb/
weight_round.rs

1use crate::Instance;
2use crate::lb::{LoadBalance, LoadBalanceError};
3use dashmap::DashMap;
4use std::sync::atomic::{AtomicUsize, Ordering};
5
6#[derive(Debug, Default)]
7pub struct WeightRoundRobinLoadBalance {
8    /// 每个服务的当前权重索引
9    current_weight: DashMap<String, AtomicUsize>,
10}
11
12impl WeightRoundRobinLoadBalance {
13    pub fn new() -> Self {
14        Self::default()
15    }
16}
17
18impl LoadBalance for WeightRoundRobinLoadBalance {
19    async fn get_instance(&self, service_id: &str) -> Result<Instance, LoadBalanceError> {
20        let instances = self.instances(service_id).await?;
21
22        if instances.is_empty() {
23            return Err(LoadBalanceError::NoAvailableInstance(
24                service_id.to_string(),
25            ));
26        }
27        if instances.len() == 1 {
28            return Ok(instances[0].clone());
29        }
30
31        // 计算总权重
32        let total_weight: u64 = instances.iter().map(|instance| instance.get_weight()).sum();
33
34        let mut current_pos = self
35            .current_weight
36            .entry(service_id.to_string())
37            .or_insert_with(|| AtomicUsize::new(0))
38            .fetch_add(1, Ordering::Relaxed);
39
40        current_pos %= total_weight as usize;
41
42        // 根据权重选择实例
43        let mut current_weight = 0;
44        for instance in &instances {
45            let weight = instance.get_weight();
46            current_weight += weight;
47            if current_pos < current_weight as usize {
48                return Ok(instance.clone());
49            }
50        }
51
52        // 理论上不会执行到这里
53        Ok(instances[0].clone())
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use crate::init;
61    #[tokio::test]
62    async fn test_weight_load_balance() {
63        let _ = init().await;
64        let lb = WeightRoundRobinLoadBalance::default();
65        for _ in 0..20 {
66            let instances = lb
67                .get_instance("conreg_client-ecdb9f5551f4f00c")
68                .await
69                .unwrap();
70            println!("instances: {:?}", instances);
71        }
72    }
73}