forked from scylladb/scylla-rust-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_load_balancing_policy.rs
64 lines (54 loc) · 1.76 KB
/
custom_load_balancing_policy.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use anyhow::Result;
use scylla::{
load_balancing::{LoadBalancingPolicy, RoutingInfo},
transport::{ClusterData, ExecutionProfile},
Session, SessionBuilder,
};
use std::{env, sync::Arc};
/// Example load balancing policy that prefers nodes from favorite datacenter
#[derive(Debug)]
struct CustomLoadBalancingPolicy {
fav_datacenter_name: String,
}
impl LoadBalancingPolicy for CustomLoadBalancingPolicy {
fn pick<'a>(
&'a self,
_info: &'a RoutingInfo,
cluster: &'a ClusterData,
) -> Option<scylla::transport::NodeRef<'a>> {
self.fallback(_info, cluster).next()
}
fn fallback<'a>(
&'a self,
_info: &'a RoutingInfo,
cluster: &'a ClusterData,
) -> scylla::load_balancing::FallbackPlan<'a> {
let fav_dc_nodes = cluster
.replica_locator()
.unique_nodes_in_datacenter_ring(&self.fav_datacenter_name);
match fav_dc_nodes {
Some(nodes) => Box::new(nodes.iter()),
// If there is no dc with provided name, fallback to other datacenters
None => Box::new(cluster.get_nodes_info().iter()),
}
}
fn name(&self) -> String {
"CustomPolicy".to_string()
}
}
#[tokio::main]
async fn main() -> Result<()> {
let uri = env::var("SCYLLA_URI").unwrap_or_else(|_| "127.0.0.1:9042".to_string());
let custom_load_balancing = CustomLoadBalancingPolicy {
fav_datacenter_name: "PL".to_string(),
};
let profile = ExecutionProfile::builder()
.load_balancing_policy(Arc::new(custom_load_balancing))
.build();
let _session: Session = SessionBuilder::new()
.known_node(uri)
.default_execution_profile_handle(profile.into_handle())
.build()
.await?;
Ok(())
}