cluster/cluster.rs
1//! Minimal `ClusterClient` walkthrough — the typed, cluster-aware client.
2//!
3//! `ClusterClient` discovers the shard topology once via `CLUSTER SLOTS`, opens
4//! one connection per shard, and routes every key to its CRC16 owner — so no
5//! command pays the server-side cross-shard forwarding hop. For the why and the
6//! perf numbers see `docs/cluster.md`.
7//!
8//! First start a cluster-mode server (any shard count ≥ 1):
9//! cargo run -p kevy --bin kevy -- --port 6004 --threads 4 --cluster
10//! Its shards then listen at 6005, 6006, 6007, 6008 — connect via any of them
11//! as the seed (here 6005); the rest are discovered automatically.
12//!
13//! Then run this example:
14//! cargo run -p kevy-client --example cluster -- 6005
15
16use kevy_client::ClusterClient;
17
18fn main() -> kevy_client::KevyResult<()> {
19 let seed: u16 = std::env::args()
20 .nth(1)
21 .and_then(|s| s.parse().ok())
22 .unwrap_or(6005);
23
24 // Connect to a seed shard; the full topology is discovered from it.
25 let mut cc = ClusterClient::connect("127.0.0.1", seed)?;
26 println!("connected — {} shard(s)", cc.shard_count());
27
28 // Each of these keys may live on a different shard; the client routes each
29 // to its owner with no -MOVED and no forwarding hop.
30 cc.set(b"user:1", b"alice")?;
31 cc.set(b"user:2", b"bob")?;
32 cc.set(b"user:3", b"carol")?;
33
34 println!("user:1 = {:?}", cc.get(b"user:1")?.map(String::from_utf8));
35
36 // INCR routes by key like any single-key command.
37 let n = cc.incr(b"counter")?;
38 println!("counter = {n}");
39
40 // DEL/EXISTS take keys that may span shards — routed per key and summed.
41 let exists = cc.exists(&[b"user:1", b"user:2", b"missing"])?;
42 println!("exists(user:1, user:2, missing) = {exists}"); // 2
43
44 let removed = cc.del(&[b"user:1", b"user:2", b"user:3"])?;
45 println!("deleted {removed} keys"); // 3
46
47 // DBSIZE / FLUSHALL are whole-cluster: kevy fans them out server-side, so
48 // one call covers every shard.
49 println!("dbsize (whole cluster) = {}", cc.dbsize()?);
50
51 Ok(())
52}