亲宝软件园·资讯

展开

java mongodb实现分布式锁 java基于mongodb实现分布式锁的代码实例

jqpeng的技术记事本 人气:0
想了解java基于mongodb实现分布式锁的代码实例的相关内容吗,jqpeng的技术记事本在本文为您仔细讲解java mongodb实现分布式锁的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,mongodb分布式锁,java,分布式锁,下面大家一起来学习吧。

原理

通过线程安全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;
    }

原理:

释放和续期锁:

   @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);
            }
        }
    }

完整代码,可到github查看 https://github.com/jadepeng/docker-pipeline/blob/main/pipeline-master/src/main/java/com/github/jadepeng/pipeline/service/impl/MongoLockService.java

加载全部内容

相关教程
猜你喜欢
用户评论