java基于mongodb实现分布式锁的示例代码
程序员文章站
2022-06-17 22:48:54
目录原理 通过线程安全findandmodify 实现锁实现 定义锁存储对象:/** * mongodb 分布式锁 */@data@noargsconstructor@allargsconstruct...
原理
通过线程安全findandmodify 实现锁
实现
定义锁存储对象:
/** * mongodb 分布式锁 */ @data @noargsconstructor @allargsconstructor @document(collection = "distributed-lock-doc") public class lockdocument { @id private string id; private long expireat; private string token; }
定义lock api:
public interface lockservice { string acquire(string key, long expiration); boolean release(string key, string token); boolean refresh(string key, string token, long expiration); }
获取锁:
@override public string acquire(string key, long expiration) { query query = query.query(criteria.where("_id").is(key)); string token = this.generatetoken(); update update = new update() .setoninsert("_id", key) .setoninsert("expireat", system.currenttimemillis() + expiration) .setoninsert("token", token); findandmodifyoptions options = new findandmodifyoptions().upsert(true) .returnnew(true); lockdocument doc = mongotemplate.findandmodify(query, update, options, lockdocument.class); boolean locked = doc.gettoken() != null && doc.gettoken().equals(token); // 如果已过期 if (!locked && doc.getexpireat() < system.currenttimemillis()) { deleteresult deleted = this.mongotemplate.remove( query.query(criteria.where("_id").is(key) .and("token").is(doc.gettoken()) .and("expireat").is(doc.getexpireat())), lockdocument.class); if (deleted.getdeletedcount() >= 1) { // 成功释放锁, 再次尝试获取锁 return this.acquire(key, expiration); } } log.debug("tried to acquire lock for key {} with token {} . locked: {}", key, token, locked); return locked ? token : null; }
原理:
- 先尝试upsert锁对象,如果成功且token一致,说明拿到锁
- 否则加锁失败
- 如果未拿到锁,但是锁已过期,尝试删除锁
- 如果删除成功,再次尝试拿锁
- 如果失败,说明锁可能已经续期了
释放和续期锁:
@override public boolean release(string key, string token) { query query = query.query(criteria.where("_id").is(key) .and("token").is(token)); deleteresult deleted = mongotemplate.remove(query, lockdocument.class); boolean released = deleted.getdeletedcount() == 1; if (released) { log.debug("remove query successfully affected 1 record for key {} with token {}", key, token); } else if (deleted.getdeletedcount() > 0) { log.error("unexpected result from release for key {} with token {}, released {}", key, token, deleted); } else { log.error("remove query did not affect any records for key {} with token {}", key, token); } return released; } @override public boolean refresh(string key, string token, long expiration) { query query = query.query(criteria.where("_id").is(key) .and("token").is(token)); update update = update.update("expireat", system.currenttimemillis() + expiration); updateresult updated = mongotemplate.updatefirst(query, update, lockdocument.class); final boolean refreshed = updated.getmodifiedcount() == 1; if (refreshed) { log.debug("refresh query successfully affected 1 record for key {} " + "with token {}", key, token); } else if (updated.getmodifiedcount() > 0) { log.error("unexpected result from refresh for key {} with token {}, " + "released {}", key, token, updated); } else { log.warn("refresh query did not affect any records for key {} with token {}. " + "this is possible when refresh interval fires for the final time " + "after the lock has been released", key, token); } return refreshed; }
使用
private lockservice lockservice; private void tryacquirelockandschedule() { while (!this.stopschedule) { // 尝试拿锁 this.token = this.lockservice.acquire(scheduler_lock, 20000); if (this.token != null) { // 拿到锁 } else { // 等待lock_expiration, 再次尝试 thread.sleep(lock_expiration); } } }
- 先尝试拿锁,如果获取到token,说明拿锁成功
- 否则可以sleep一段时间后再拿锁
到此这篇关于java基于mongodb实现分布式锁的示例代码的文章就介绍到这了,更多相关java mongodb实现分布式锁内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!