当前位置: 首页 > article >正文

基于 Redisson 分布式锁 实现报名人数限制功能

1:pom依赖

        <!-- redisson -->
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.6.5</version>
        </dependency>

2:相关配置

2.1 RedissonConfig

package com.ly.cloud.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class RedissonConfig {

    @Value("${spring.redis.host}")
    private String address;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://" + address + ":"+port)
                .setPassword(password)
                .setTimeout(10000)
                .setRetryAttempts(5)
                .setRetryInterval(2000)
                .setConnectionPoolSize(64)
                .setConnectionMinimumIdleSize(24)
                // 保持连接活动
                .setKeepAlive(true)
                // 发送PING命令的间隔时间;
                .setPingConnectionInterval(30000);

        return Redisson.create(config);
    }
}

2.2 RedissonDistributedLock

package com.ly.cloud.components;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedissonDistributedLock {

    @Resource
    private RedissonClient redissonClient;

    public boolean tryLock(String lockKey, long expireTime, long waitTime) throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock(waitTime, expireTime, TimeUnit.MILLISECONDS);
    }

    public void releaseLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

3:业务代码

    @Override
    public Boolean insertLectureRegistration(String lectureId) throws InterruptedException {
        String loginUserId = LoginUserUtil.getLoginUserId();
        // 判断当前 用户是否已经报名该讲座
//        if (lectureMessageMapper.getIsRegistrationLectrure(lectureId,loginUserId) > 0) {
//            throw new BusinessException("用户:" + loginUserId + "已报名成功,无需第二次报名!");
//        }
        LectureRegistration registration = new LectureRegistration();
        registration.setId(IdUtil.simpleUUID());
        registration.setUserId(loginUserId);
        registration.setUserName(userMapper.getUserName(loginUserId));
        registration.setRegistrationTime(DateTimeUtils.getTimeStamp());
        String departmentId = departmentMapper.getDepartmentById(loginUserId);
        registration.setRegistrationDepartmentNumber(departmentId);
        registration.setRegistrationDepartmentName(departmentMapper.getDepartmentName(departmentId));
        registration.setLectureNumber(lectureId);
        registration.setDeleted("1");

        int total = lectureMessageMapper.getRegistrationPeopleTotal(lectureId);
        if (total == 0) {
            return lectureMessageMapper.insertLectureRegistration(registration) > 0;
        }
        String lockKey = lectureId + "stock";
        // 只在 Redis 不存在时初始化库存
        Boolean stockExists = stringRedisTemplate.hasKey(lockKey);
        if (Boolean.FALSE.equals(stockExists)) {
            stringRedisTemplate.opsForValue().setIfAbsent(lockKey, String.valueOf(total));
        }
        boolean locked = redissonDistributedLock.tryLock(lectureId, 1000, 5000);
        try {
            if (locked) {
                stringRedisTemplate.watch(lockKey);
                String stockStr = stringRedisTemplate.opsForValue().get(lockKey);
                if (stockStr == null) {
                    throw new BusinessException("讲座报名名额数据异常");
                }
                int stock = Integer.parseInt(stockStr);

                if (stock > 0) {
                    stringRedisTemplate.setEnableTransactionSupport(true);
                    stringRedisTemplate.multi();
                    Long realStock = stringRedisTemplate.opsForValue().increment(lockKey, -1);
                    List<Object> results = stringRedisTemplate.exec();
                    if (!CollectionUtils.isEmpty(results)) {
                        logger.info("讲座报名名额剩余:{}", realStock);
                        return lectureMessageMapper.insertLectureRegistration(registration) > 0;
                    } else {
                        throw new BusinessException("讲座报名名额已用完,无法报名!");
                    }
                } else {
                    throw new BusinessException("讲座报名名额已用完,无法报名!");
                }
            }
        } catch (Exception e) {
            throw new BusinessException("报名失败:", e);
        } finally {
            if (locked) {
                redissonDistributedLock.releaseLock(lectureId);
            }
        }
        return true;
    }

4:并发测试


http://www.kler.cn/a/552905.html

相关文章:

  • Python----数据结构(栈:列表栈,链栈。初始化,入栈,出栈,获取栈长度,判断是否为空,访问栈顶元素)
  • GcExcel
  • K8S的Dashboard登录及验证
  • 【数据挖掘】--算法
  • Python 学习之旅:高级阶段(十)数据库操作 MongoDB
  • Spark算子:大数据处理的魔法棒
  • Spring Bean 生命周期
  • 机器学习小项目之鸢尾花分类
  • ubuntu系统中新增硬盘挂载硬盘
  • SVN 创建版本库
  • 力扣 买卖股票的最佳时机
  • PyCharm Terminal 自动切换至虚拟环境
  • module ‘cv2.dnn‘ has no attribute ‘DictValue‘解决办法
  • Java并发编程面试题:锁(17题)
  • AI时代的前端开发:新兴职位与效率提升工具
  • QT异步编程之QMetaObject::invokeMethod
  • 极限网关 INFINI Gateway 配置文件核心解读
  • 基于ffmpeg+openGL ES实现的视频编辑工具-解码(四)
  • 【数据结构初阶第十二节】设计循环队列
  • transfmer学习认识