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
65
66
67
68
//! # Pattern — Work Queue
//!
//! Demonstrates the competing consumers (work queue) pattern. Tasks are
//! enqueued, and two workers pull and process them independently. Each task
//! is consumed by exactly one worker.
//!
//! ## Expected Output
//!
//! ```text
//! Enqueued 6 tasks
//! Worker-1 processed: task-0
//! Worker-2 processed: task-1
//! Worker-1 processed: task-2
//! ...
//! ```
//!
//! ## Running
//!
//! Requires a running KubeMQ broker. By default connects to `localhost:50000`.
//! Override with `KUBEMQ_ADDRESS`:
//!
//! ```bash
//! KUBEMQ_ADDRESS=my-host:50000 cargo run --example pattern_work_queue
//! ```
use kubemq::prelude::*;
use kubemq::QueueMessageBuilder;
#[tokio::main]
async fn main() -> kubemq::Result<()> {
let client = KubemqClient::builder()
.host("localhost")
.port(50000)
.build()
.await?;
let channel = "patterns.work_queue.example";
// Enqueue tasks
for i in 0..6 {
let msg = QueueMessageBuilder::new()
.channel(channel)
.body(format!("task-{}", i).into_bytes())
.build();
client.send_queue_message(msg).await?;
}
println!("Enqueued 6 tasks");
// Worker 1 pulls a batch
let worker1_msgs = client.receive_queue_messages(channel, 3, 5, false).await?;
for m in &worker1_msgs {
println!(
"Worker-1 processed: {}",
String::from_utf8_lossy(&m.body)
);
}
// Worker 2 pulls remaining
let worker2_msgs = client.receive_queue_messages(channel, 3, 5, false).await?;
for m in &worker2_msgs {
println!(
"Worker-2 processed: {}",
String::from_utf8_lossy(&m.body)
);
}
client.close().await?;
Ok(())
}