论JAVA实现MYSQL 行级锁(分布式锁实现方案一)

Posted 盗帅_tim

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了论JAVA实现MYSQL 行级锁(分布式锁实现方案一)相关的知识,希望对你有一定的参考价值。

 @Override
    @Transactional
    public String getCustomerId() {
//        return String.valueOf(getSequenceId(SEQ_CUSTOMER_ITEM_CODE.seqName));
        String type=SEQ_CUSTOMER_ITEM_CODE.seqName;

        if (!sequenceValueMap.containsKey(type)) {
            SequenceDO sequenceDO = sequenceDOMapper.getBySeqNameForUpdate(type);
            LOGGER.info(Thread.currentThread().getName()+"===="+sequenceDO.getCurrentValue());
            sequenceValueMap.put(type, sequenceDO);
            //更新值
            int value = sequenceDO.getCurrentValue();
            sequenceDOMapper.updateSequenceValue(type, sequenceDO.getCurrentValue() + sequenceDO.getStep());
            sequenceDO.setCurrentValue(value + 1);
            LOGGER.info(Thread.currentThread().getName()+"----------->CurrentSequenceType:[{}],value:[{}]", type, sequenceDO.getCurrentValue());

            return sequenceDO.getCurrentValue()+"";
        } else {
            SequenceDO sequenceDO = sequenceValueMap.get(type);
            int value = sequenceDO.getCurrentValue() + 1;
            if (value % sequenceDO.getStep() == 0) {
                //更新值
                SequenceDO temp = sequenceDOMapper.getBySeqNameForUpdate(type);
                LOGGER.info(Thread.currentThread().getName()+"----------->CurrentSequenceType:[{}],value:[{}]", type, temp.getCurrentValue());
                sequenceDOMapper.updateSequenceValue(type, temp.getCurrentValue() + temp.getStep());
                sequenceValueMap.put(type, temp);
            } else {
                sequenceDO.setCurrentValue(value);
            }
            return value+"";
        }
    }

  使用行级锁 一定要注意 加上事务控制   mysql 行级锁才会起效,才会以排他的形式  访问

-12-26 20:03:20.562  INFO  39993---[Thread-22]   c.s.m.s.i.SequenceServiceImpl - Thread-22====100198439
2019-12-26 20:03:20.572  INFO  39993---[Thread-22]   c.s.m.s.i.SequenceServiceImpl - Thread-22----------->CurrentSequenceType:[sequenceCustomerInfo],value:[100198440]
2019-12-26 20:03:20.577  INFO  39993---[ZkClient-EventThread-23-127.0.0.1:2181]   o.I.z.ZkEventThread - Terminate ZkClient event thread.
2019-12-26 20:03:20.580  INFO  39993---[Thread-23]   c.s.m.s.i.SequenceServiceImpl - Thread-23====100198440
2019-12-26 20:03:20.581  INFO  39993---[DubboShutdownHook]   o.a.z.ZooKeeper - Session: 0x100048539830052 closed
2019-12-26 20:03:20.581  INFO  39993---[main-EventThread]   o.a.z.ClientCnxn - EventThread shut down
100198440
2019-12-26 20:03:20.589  INFO  39993---[Thread-23]   c.s.m.s.i.SequenceServiceImpl - Thread-23----------->CurrentSequenceType:[sequenceCustomerInfo],value:[100198441]

 

以上是关于论JAVA实现MYSQL 行级锁(分布式锁实现方案一)的主要内容,如果未能解决你的问题,请参考以下文章

转 MySQL中的行级锁,表级锁,页级锁

MySQL表级锁行级锁与多粒度锁(意向锁)

事务隔离实现并发控制:MySQL系列之十

MySQL锁的用法之行级锁

Mysql(16)—数据库的全局锁表级锁和行级锁的全面深度解析

MySQL——并发控制(锁)