1 Star 2 Fork 3

Rey Wong / 最佳实践

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
redis作为分布式事务锁.md 1.25 KB
一键复制 编辑 原始数据 按行查看 历史
wr090097 提交于 2021-07-19 15:26 . init

加锁

public String lockAndReturnKeyNew(String key, long timeout) {
        long orginalTimeout = timeout;
        long checkTimeout = timeout;
        String lockName = key + "_lock";

        while (checkTimeout >= 0) {
            long expires = System.currentTimeMillis() + checkTimeout + 1;
            String expiresStr = String.valueOf(expires);
            String LOCK_SUCCESS = "OK";
            String SET_IF_NOT_EXIST = "NX";
            String SET_WITH_EXPIRE_TIME = "PX";
            String result = redisInterface.set(lockName, expiresStr, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, Long.valueOf(orginalTimeout).intValue() / 1000);
            if (LOCK_SUCCESS.equals(result)) {
                return lockName;
            }

            checkTimeout -= 10;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                LOGGER.error("当前线程被强制中断,请检查.", e);
                Thread.currentThread().interrupt();

            }
        }
        return null;
    }

解锁

 public void unlock(String key) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("key:{}已清除锁成功", key);
        }
        redisInterface.del(key + "_lock");
    }
1
https://gitee.com/reywong/best_practices.git
git@gitee.com:reywong/best_practices.git
reywong
best_practices
最佳实践
master

搜索帮助