Send & Receive
Send a message to a KubeMQ queue channel and pull it back with the Rust SDK for basic queue messaging.
Overview
Queue send/receive is the foundational operation for guaranteed-delivery, point-to-point messaging: you reach for it whenever work needs to survive past the moment it's created and be handled by exactly one consumer, not broadcast to every subscriber. Unlike pub/sub, a queued message sits durably on the broker until something pulls it, so the producer and consumer never need to be online at the same time — a slow or offline worker adds latency, it doesn't drop the message.
This tutorial builds the smallest possible version of that round trip: send_queue_message enqueues a message on a channel, and receive_queue_messages pulls it back with a bounded wait_time_seconds. The is_peek flag controls whether receiving consumes the message — false removes it from the queue on delivery, while true reads it without removing it.
Gotchas: with is_peek set to false, the message is considered handled the moment it's delivered — if your handler crashes right after receiving, that message is already gone with no chance to retry. Polling an empty queue isn't an error; it just returns an empty vector once the timeout elapses. And max_messages caps how many messages one call can return, so don't assume a single receive_queue_messages call drains the whole queue.
Prerequisites
- KubeMQ server running on
localhost:50000 - Rust SDK installed (
cargo add kubemq)
Code
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 = "rust-queues.send-receive";
let msg = QueueMessageBuilder::new()
.channel(channel)
.body(b"Hello Queue!".to_vec())
.metadata("queue-metadata")
.build();
let result = client.send_queue_message(msg).await?;
println!(
"Sent: message_id={}, sent_at={}",
result.message_id, result.sent_at
);
let messages = client.receive_queue_messages(channel, 10, 5, false).await?;
for m in &messages {
println!(
"Received: id={}, body={}",
m.id,
String::from_utf8_lossy(&m.body)
);
}
println!("Total received: {}", messages.len());
client.close().await?;
Ok(())
}How It Works
send_queue_messagepersists the message and returns aQueueSendResultwith server timestamps.receive_queue_messagespulls up tomax_messageswith await_time_secondstimeout.- Setting
is_peektofalseconsumes messages;truereads without consuming. - Review timeouts, channel names, and client IDs before running against shared environments.
- Run the program while the server from the prerequisites is available.
Related
Was this page helpful?