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

基于 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:并发测试

相关文章:

  • EasyRTC智能硬件:实时畅联、沉浸互动、消音护航
  • 数据结构之栈和队列
  • 为什么WebGPU渲染通道描述符使用TextureView而非直接操作Texture?
  • 面试题复习
  • PyTorch Tensor 形状变化操作详解
  • 告别第三方云存储!用File Browser在Windows上自建云盘随时随地访问
  • 【git】初识git概念及命令,工作场景流程
  • .NET软件开发框架简记
  • Delphi语言的软件工程
  • std::ranges::merge std::merge std::inplace_merge
  • 基于SpringBoot实现的大学社团平台系统实现功能八
  • C++ 线程和线程管理
  • Hadoop 基础原理
  • 小狐狸ai3.1.2版本源码无授权版本内 含搭建教程+各种上线教程
  • sql server 数据库 锁教程及锁操作
  • DeepSeek - R1:模型架构深度解析
  • 汉诺塔问题详解:递归与分治的经典案例
  • S7-200中的软件及编程
  • 【强化学习的数学原理】第08课-值函数近似-笔记
  • 用deepseek学大模型08-卷积神经网络(CNN)
  • 域名和网站空间怎么做解析/西安今天出大事
  • 从做系统网站的收藏怎么找/想要推广网页
  • 智能家居型网站开发/广告策划方案范文
  • 一个大型的网站建设/廊坊自动seo
  • 手机 网站编辑器/宁波seo搜索引擎优化
  • 龙岩网站建设较好的公司/论坛推广