Package cn.boboweike.carrot.lock.nosql
Class MongoLockProvider
- java.lang.Object
-
- cn.boboweike.carrot.lock.nosql.MongoLockProvider
-
- All Implemented Interfaces:
LockProvider
public class MongoLockProvider extends Object implements LockProvider
Adapted from https://github.com/lukas-krecan/ShedLock/blob/master/providers/mongo/shedlock-provider-mongo/src/main/java/net/javacrumbs/shedlock/provider/mongo/MongoLockProvider.java Distributed lock using MongoDB >= 2.6. Requires mongo-java-driver > 3.4.0It uses a collection that contains documents like this:
{ "_id" : "lock name", "lockUntil" : ISODate("2017-01-07T16:52:04.071Z"), "lockedAt" : ISODate("2017-01-07T16:52:03.932Z"), "lockedBy" : "host name" }lockedAt and lockedBy are just for troubleshooting and are not read by the code- Attempts to insert a new lock record. As an optimization, we keep in-memory track of created lock records. If the record has been inserted, returns lock.
- We will try to update lock record using filter _id == name AND lock_until <= now
- If the update succeeded (1 updated document), we have the lock. If the update failed (0 updated documents) somebody else holds the lock
- When unlocking, lock_until is set to now.
-
-
Field Summary
-
Fields inherited from interface cn.boboweike.carrot.lock.LockProvider
LOCK_UNTIL, LOCKED_AT, LOCKED_BY
-
-
Constructor Summary
Constructors Constructor Description MongoLockProvider(com.mongodb.client.MongoCollection<org.bson.Document> collection)Uses Mongo to coordinate locks
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanextend(String name, int durationInSeconds, String lockedBy)booleanlock(String name, int durationInSeconds, String lockedBy)booleanunlock(String name)
-
-
-
Method Detail
-
lock
public boolean lock(String name, int durationInSeconds, String lockedBy)
- Specified by:
lockin interfaceLockProvider
-
extend
public boolean extend(String name, int durationInSeconds, String lockedBy)
- Specified by:
extendin interfaceLockProvider
-
unlock
public boolean unlock(String name)
- Specified by:
unlockin interfaceLockProvider
-
-