V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
AnswerNo2
V2EX  ›  程序员

分布式锁

  •  
  •   AnswerNo2 · Jul 24, 2019 · 1384 views
    This topic created in 2479 days ago, the information mentioned may be changed or developed.
    之前写的一个生产上的分布式锁,你们会怎么写?

    public static boolean tryGetLock(String lockKey, String requestId, int waitTimeSecond, int expireTime) {

    // 获取锁的超时时间,超过这个时间则放弃获取锁
    long end = System.currentTimeMillis() + (waitTimeSecond * 1000);
    while (System.currentTimeMillis() < end) {
    boolean flag = getRedis().opsForValue().setIfAbsent(lockKey, requestId);
    if (flag) {
    RedisUtil.expire(lockKey, expireTime);
    return flag;
    }
    try {
    Thread.sleep(10);
    } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    }
    }
    return false;
    }
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3766 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 04:50 · PVG 12:50 · LAX 21:50 · JFK 00:50
    ♥ Do have faith in what you're doing.