高并发解决方案1

高并发解决方案1

技术栈

  • SpringBoot
  • SpringWebMvc
  • MongoDB
  • Redis
  • MybatisPlus

场景流程说明

邀请码未使用完毕:

image-20220819164725656

使用完毕:

image-20220819164919814

代码

controller

@PostMapping("/useAnInvitationCode")
public ResponseResult useAnInvitationCode(String invitationCode) {
    return publicService.useAnInvitationCode(invitationCode);
}

service

/**
 * 使用邀请码
 * @param invitationCode 邀请码
 * @return
 */
ResponseResult useAnInvitationCode(String invitationCode);

serviceImpl

    public ResponseResult useAnInvitationCode(String invitationCode) {
        String name = InvitationCode.class.getName();
        //缓存加锁
        String key = invitationCode + ":" + "LOCK";
        try {
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, invitationCode, 100, TimeUnit.MILLISECONDS);

            if (Boolean.TRUE.equals(lock)) {
                Jedis jedis = new Jedis("localhost", 6379);
                Boolean aBoolean = RedisInventoryUtils.ReduceInventory(jedis, invitationCode);
                String msg = jedis.get(invitationCode);
                if (ObjectUtils.isEmpty(msg)) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
                }
                int anInt = Integer.parseInt(jedis.get(invitationCode));
                log.info("测试秒杀活动:{}", anInt);
                return ResponseResult.okResult(anInt);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.SECOND_KILL_FAILED);
            }
        } finally {
            redisTemplate.delete(key);
        }
    }

utils

public static Boolean ReduceInventory(Jedis jedis, String key) {
    //非空校验
    String msg = jedis.get(key);
    if (ObjectUtils.isEmpty(msg)) {
        return false;
    }
    //获取剩余库存
    int anInt = Integer.parseInt(jedis.get(key));
    if (anInt > 0) {
        //扣减库存
        jedis.set(key, String.valueOf(anInt - 1));
        //关闭通道
        jedis.close();
        return true;
    } else if (anInt == 0) {
        //删除库存
        jedis.del(key);
        //关闭通道
        jedis.close();
        return false;
    } else {
        //关闭通道
        jedis.close();
        return true;
    }
}

因为重点不是备份就不分享持久化和获取队列过程了

THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容