前面文章提到实现分布式锁有3种方式,一是基于数据库,二是基于Redis,三是基于zookeeper,前面的文章已经详细介绍过基于Redis实现分布式锁的方法。本文将简单介绍基于数据库的实现方式。

一、建立数据库lock表:

二、利用update修改STATUS字段进行获取锁以及释放锁

    update online_xdclass.lock set STATUS=#{lockStatus,jdbcType=VARCHAR}
    where LOCKNAME=#{lockName,jdbcType=VARCHAR} and STATUS=#{lockStatusTmp,jdbcType=VARCHAR}

三、获取锁方法

    public Integer tryLock(String lockName, String lockStatus, String lockStatusTmp) {
        Integer integer = sequenceMapper.updateLock(lockName, lockStatus, lockStatusTmp);
        return integer;
    }

四、释放锁方法

    public Integer tryUnLock(String lockName, String lockStatus, String lockStatusTmp) {
        Integer integer = sequenceMapper.updateLock(lockName, lockStatus, lockStatusTmp);
        return integer;
    }

五、测试代码

    public String businessDealByLock() {
        try {
            //获取锁
            Integer integer = tryLock("测试锁", "1", "0");
            if(integer>0)
                System.out.println("i get the lock!");
            else
                System.out.println("sorry,i can't get the lock!");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            tryUnLock("测试锁", "0", "1");
            System.out.println("i released the lock!");
        }
        return "测试成功!";
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐