4 releases (2 breaking)

0.4.0 Jul 4, 2024
0.3.0 Jun 22, 2023
0.2.2 Jan 10, 2023
0.1.0 Jan 9, 2023

#266 in Concurrency

Download history 8/week @ 2024-09-10 5/week @ 2024-09-17 15/week @ 2024-09-24 2/week @ 2024-10-01

270 downloads per month

MIT license

12KB
229 lines

Distributed mutually exclusive locks in MongoDB.

Crates.io docs.rs

This crate contains only async implementation. If you need a synchronous version, use mongo-lock crate.

This implementation relies on system time. Ensure that NTP clients on your servers are configured properly.

Installation

Add this crate to Cargo.toml

[dependencies]
mongo_lock_async = "0"

Usage

#[tokio::main]
async fn main() {
    let mongo = mongodb::Client::with_uri_str("mongodb://localhost").await.unwrap();

    // We need to ensure that mongodb collection has a proper index.
    mongo_lock_async::prepare_database(&mongo).await.unwrap();

    if let Ok(Some(lock)) =
        mongo_lock_async::Lock::try_acquire(
            &mongo,
            "my-key",
            std::time::Duration::from_secs(30)
        ).await
    {
        println!("Lock acquired.");

        // Release the lock before ttl expires to allow others to acquire it.
        lock.release().await.ok();
    }
}

Dependencies

~15–24MB
~373K SLoC