A Tokio-based async API. Connect to a single server, acquire a key, and release it right away.
use std::time::Duration;
use ticketing::TicketBroker;
let broker = TicketBroker::connect(["127.0.0.1:5225"]);
broker.wait_ready(Duration::from_secs(5)).await;
let wait = Duration::from_secs(5);
let lease = Duration::from_secs(30);
let ticket = broker.acquire("key", wait, lease).await.unwrap();
ticket.release().await.unwrap();
println!("pass");An example that verifies that the balance always returns to its starting value even when several tasks repeat deposits/withdrawals while mutually excluding each other via a per-account lock. TicketBroker is Clone, so it can be shared across multiple tasks.
async fn transaction(broker: &TicketBroker, account: usize, delta: i64) {
let key = format!("account-{account}");
let _ticket = match broker.acquire(&key, WAIT, LEASE).await {
Ok(ticket) => Some(ticket),
Err(e) => {
tracing::error!("account {account} acquire failed: {e}");
return;
}
};
// safe critical section only while the lock is held
let before = balances[account];
tokio::task::yield_now().await;
balances[account] = before + delta;
// dropping the ticket releases it automatically in the background (can be skipped if immediate release isn't needed)
let (action, sign) = if delta < 0 { ("withdraw", '-') } else { ("deposit", '+') };
tracing::info!("account {account} {action} {sign}${AMOUNT} -> ${}", balances[account]);
}See the full examples in tests/example_simple.rs, tests/example_bank.rs, tests/bench_test.rs.