真实项目中使用悲观锁或者乐观锁来解决并发问题

本人在金融公司任职,今天来分享下关于转账的一些并发处理问题,这节内容,我们不聊实现原来,就单纯的看看如何实现
废话不多说,咱们直接开始,首先我会模拟一张转账表
如下图所示:


image.png

一张简单的账户表,有name,账户余额等等,接下来我将用三种锁的方式来实现下并发下的互相转账
一:悲观锁:
概念我就在这里不说了,很简单,直接上代码
接口层:

void transfer(Integer sourceId, Integer targetId, BigDecimal money);

实现层:

/**
     * 转账操作(使用悲观锁的方式执行转账操作)
     * source:转出账户
     * target:转入专户
     * money:转账金额
     * @param sourceId
     * @param targetId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(Integer sourceId, Integer targetId, BigDecimal money) {
        RyxAccount source;
        RyxAccount target;
        //处理死锁问题,每次从小到大执行
        if (sourceId <= targetId){
            source = getAccount(sourceId);
            target = getAccount(targetId);
        }else{
            target = getAccount(targetId);
            source = getAccount(sourceId);
        }

        if (source.getMoney().compareTo(money) >=0){
            source.setMoney(source.getMoney().subtract(money));
            target.setMoney(target.getMoney().add(money));

            updateAccount(source);
            updateAccount(target);
        }else{
            log.error("账户[{}]余额[{}]不足,不允许转账", source.getId(),source.getMoney());
        }

    }

        private RyxAccount getAccount(Integer sourceId) {
        return this.ryxAccountService.getRyxAccountByPrimaryKeyForUpdate(sourceId);
    }

    private void updateAccount(RyxAccount account) {
        account.setUpdateTime(new Date());
        this.ryxAccountService.updateByPrimaryKey(account, account.getId());
    }

mapper层:

<select id="getRyxAccountByPrimaryKeyForUpdate" resultMap="base_result_map" >
        select <include refid="base_column_list" /> from `ryx_account` where `id`=#{id} for update
    </select>

测试代码:我同时启动5个线程,来执行转账操作

@Test
    public void transferTest() throws InterruptedException {
        Integer zhangsanAccountId = 315;
        Integer lisiAccountId = 316;
        Integer wangwuAccountId =317;
        Integer zhaoliuAccountId = 318;

        BigDecimal money = new BigDecimal(100);
        BigDecimal money1 = new BigDecimal(50);
        //zhangsan转lisi100
        Thread t1 = new Thread(() ->{
            accountService.transfer(zhangsanAccountId, lisiAccountId, money);
        });

        //lisi转wangwu100
        Thread t2 = new Thread(() ->{
            accountService.transfer(lisiAccountId, wangwuAccountId, money);
        });

        //wangwu转zhaoliu 100
        Thread t3 = new Thread(() ->{
            accountService.transfer(wangwuAccountId, zhaoliuAccountId, money);
        });

        //zhoaliu转zhangsan 100
        Thread t4 = new Thread(() ->{
            accountService.transfer(zhaoliuAccountId, zhangsanAccountId, money);
        });

        //zhangsan转zhaoliu 50
        Thread t5 = new Thread(() ->{
            accountService.transfer(zhangsanAccountId, zhaoliuAccountId, money1);
        });


        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

        t1.join();
        t2.join();
        t3.join();
        t4.join();
        t5.join();
    }

启动我们来看看结果


image.png

执行结果符合预期
悲观锁的主要逻辑就是在查询的时候使用select * ..... for update 语句,还有一点,子啊账户查询的时候,我们按照主键的顺序执行了排序后进行处理,否则会发生死锁,原理我们就先不介绍了,主要就是先看看如何处理

二:悲观锁:这个情况下,我就就需要在数据库中增加一个版本号,


image.png

接着看代码
接口层:

/**
     * 乐观锁方式
     * @param sourceId 转出账户
     * @param targetId 转入账户
     * @param money  转账金额
     */
    void transferOptimistic(Integer sourceId, Integer targetId, BigDecimal money);

实现层:

/**
     * 使用乐观锁执行
     * @param sourceId
     * @param targetId
     * @param money
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferOptimistic(Integer sourceId, Integer targetId, BigDecimal money) {
        RyxAccount source = getAccountOptimistic(sourceId);
        RyxAccount target = getAccountOptimistic(targetId);


        if (source.getMoney().compareTo(money) >=0){
            source.setMoney(source.getMoney().subtract(money));
            target.setMoney(target.getMoney().add(money));

            // 先锁 id 较大的那行,避免死锁
            int result1, result2;
            if (source.getId() <=target.getId()){
                result1 = updateOptimisticAccount(source,source.getVersion());
                result2 = updateOptimisticAccount(target,target.getVersion());
            }else{
                result2 = updateOptimisticAccount(target,target.getVersion());
                result1 = updateOptimisticAccount(source,source.getVersion());
            }

            if (result1 < 1 || result2 < 1) {
                throw new RuntimeException("转账失败,重试中....");
            } else {
                log.info("转账成功");
            }
        }else{
            log.error("账户[{}]余额[{}]不足,不允许转账", source.getId(),source.getMoney());
        }

    }
    private int updateOptimisticAccount(RyxAccount account,Integer version) {
        account.setUpdateTime(new Date());
        return this.ryxAccountService.updateOptimisticByPrimaryKey(account, account.getId(),version);
    }

mapper层:

<update id="updateOptimisticByPrimaryKey" parameterType="com.ryx.xiaoxin_distribute.entity.pojo.RyxAccount">
        UPDATE `ryx_account`
        <set>
            <if test="bean.name != null">
                `name` = #{bean.name},
            </if>
            <if test="bean.money != null">
                `money` = #{bean.money},
            </if>
            <if test="bean.createTime != null">
                `createTime` = #{bean.createTime},
            </if>
            <if test="bean.updateTime != null">
                `updateTime` = #{bean.updateTime},
            </if>
            version = version +1
        </set>
        where `id`=#{id}
        and version = #{bean.version}
    </update>

主要执行的sql语句就是update set xxxx version = version+1 where version = #{bean.version}
我们来看看执行结果,测试代码就不展示了,和上面一样


image.png

可以看到报错了,需要重试,所以如果你需要使用乐观锁的话需要,有重试机制,而且重试次数比较多,所以对于转账操作,就不适合使用
乐观锁去解决
三:分布式锁:
接下来,我们在用第三种方式处理一下,就是使用分布式锁,分布式锁可以用redis分布式锁,也可以使用zk做分布式锁,比较简单
我们就直接上代码吧
接口层:

/**
     * 分布式锁方式
     * @param sourceId 转出账户
     * @param targetId 转入账户
     * @param money  转账金额
     */
    void transferDistributed(Integer sourceId, Integer targetId, BigDecimal money);

实现层:

/**
     * 使用分布式锁执行
     * @param sourceId
     * @param targetId
     * @param money
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferDistributed(Integer sourceId, Integer targetId, BigDecimal money) {
        try {
            accountLock.lock();
            distributedAccount(sourceId,targetId,money);
        } catch (Exception e) {
            log.error(e.getMessage());
            //throw new RuntimeException("错误啦");
        } finally {
            accountLock.unlock();
        }
    }

private void distributedAccount(Integer sourceId, Integer targetId, BigDecimal money) {
        RyxAccount source;
        RyxAccount target;

        //解决死锁问题
        if (sourceId <= targetId){
            source = this.ryxAccountService.getRyxAccountByPrimaryKey(sourceId);
            target = this.ryxAccountService.getRyxAccountByPrimaryKey(targetId);
        }else{
            target = this.ryxAccountService.getRyxAccountByPrimaryKey(targetId);
            source = this.ryxAccountService.getRyxAccountByPrimaryKey(sourceId);
        }

        if (source.getMoney().compareTo(money) >=0){
            source.setMoney(source.getMoney().subtract(money));
            target.setMoney(target.getMoney().add(money));

            updateAccount(source);
            updateAccount(target);
        }else{
            log.error("账户[{}]向[{}]转账余额[{}]不足,不允许转账", source.getId(),target.getId(),source.getMoney());
            throw new RuntimeException("账户余额不足,不允许转账");
        }
    }

      @Override
    public void afterPropertiesSet() throws Exception {
        if (accountLock == null){
             accountLock = this.redisLockRegistry.obtain("account-lock");
        }
    }

分布式锁的配置,可以参考我之前的笔记,这里在简单贴出代码

@Configuration
public class RedisLockConfiguration {

    @Bean
    public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
        RedisLockRegistry redisLockRegistry = new RedisLockRegistry(redisConnectionFactory, "spring-cloud", 5000L);
        return redisLockRegistry;
    }

}
``
写下来还是比较简单,今天只是大概在代码实现方面做了介绍,`咩有涉及到原理,原理分析篇涉及到的内容比较多,等后续整理出来再分享
再说说我们公司用的方法,我锁在职的是金融公司,转账操作特别频发,而且每天几十个亿的资金也很正常
而我们公司在处理转账的逻辑中,涉及到并发的时候,就是使用的悲观锁的方式来处理的.
今天就分享到这里!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355