mongodb-lock
A really light-weight way to get distributed locks with a nice API if you're already using MongoDB.
Version 1.0 !!!
Please note that the API has changed for v1.0 (compared to v0.4 and previously). This fits in with MongoDB Driver v3 and above.
Synopsis
Create a connection to your MongoDB database, and use it to create a lock object:
const mongodb = const mongoDbLock = const url = 'mongodb://localhost:27017/'const dbName = 'test'const colName = 'locks'const lockName = 'database-backup' mongodbMongoClient
Now, acquire the lock:
lock
Once you have a lock, you have a 30 second timeout until the lock is released. You can release it earlier by supplying the code:
lock
MongoDB Indexes
You should make sure any indexes have been added to the collection to make the queries faster:
lock
Multiple Locks
Multiple locks can use the same collection and operate quite independently:
const dbBackupLock = const hourlyStats = const sendInvoices =
Options
Currently there are two options: timeout
and removeExpired
timeout
Currently the default is 30 seconds, but you can change it (in milliseconds):
// lock for 60 secondsconst opts = timeout : 60 * 1000 // create the lock objectconst uploadFiles = // acquire the lockuploadFiles
removeExpired
Currently the default value is false
.
When set to true
this will remove expired lock records from MongoDB instead of modifying them.
// remove old locks from MongoDBconst opts = removeExpired : true // create the lock objectconst cleanUpCacheDirs = // all old locks are now deleted, rather than just hanging around
Changelog
1.0.0 (2019-08-08)
- [FIX] made sure MongoDB Lock works with the MongoDB driver >v3
- Yay - v1.0.0!
0.4.0 (2017-03-07)
- Allow option so old locks are removed rather than updated (thanks Aiden Keating)
0.3.0 (2017-03-07)
- Support for the MongoDB Driver v2 (thanks Aiden Keating)
- Better ReadMe (thanks Marek)
- Better ReadMe (thanks Krasiyan Nedelchev)
0.2.0 (2015-04-17)
- [FIX] made sure that a 2nd .release() doesn't return ok (ie. it didn't do anything)
0.1.0 (2015-04-17)
- [NEW] added ability to add indexes to MongoDB
- [NEW] added lock()
- [NEW] added release()
Author
$ npx chilts
╒════════════════════════════════════════════════════╕
│ │
│ Andrew Chilton (Personal) │
│ ------------------------- │
│ │
│ Email : andychilton@gmail.com │
│ Web : https://chilts.org │
│ Twitter : https://twitter.com/andychilton │
│ GitHub : https://github.com/chilts │
│ GitLab : https://gitlab.org/chilts │
│ │
│ Apps Attic Ltd (My Company) │
│ --------------------------- │
│ │
│ Email : chilts@appsattic.com │
│ Web : https://appsattic.com │
│ Twitter : https://twitter.com/AppsAttic │
│ GitLab : https://gitlab.com/appsattic │
│ │
│ Node.js / npm │
│ ------------- │
│ │
│ Profile : https://www.npmjs.com/~chilts │
│ Card : $ npx chilts │
│ │
╘════════════════════════════════════════════════════╛
License
MIT - http://chilts.mit-license.org/2014/
(Ends)