使用springBoot+redis+rabbitMQ构建电商基础秒杀项目

【秒杀系统业务分析

在秒杀系统当中有两个核心的表:秒杀商品与秒杀明细,具体的逻辑是一个用户秒杀商品的库存减一,秒杀明细的记录增加一条。这两步作是处于同一事务之中。

当秒杀日期尚未达到会提示用户秒杀尚未开始;
当用户多次秒杀同一商品会提示用户重复秒杀;
当秒杀日期过期或者秒杀商品的库存为零会提示用户秒杀结束。

一、项目环境搭建

创建一个springBoot项目

添加模板依赖

<!-- 添加thymeleaf模板依赖 -->
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
	    <groupId>redis.clients</groupId>
	    <artifactId>jedis</artifactId>
	</dependency>
	<!--mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.2</version>
        </dependency>
        <!--连接池依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
	<!-- 添加 fastjson依赖 -->
	<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.38</version>
		</dependency>

thymeleaf的配置

# 是否开启缓存
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
#url前缀
spring.thymeleaf.prefix=classpath:/templates/
#url后缀
spring.thymeleaf.suffix=.html

集成Mybatis

2.添加配置

#druid
spring.datasource.url=jdbc:mysql://localhost:3306/imooc?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=westos
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=2
spring.datasource.initialSize=1
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20

基本的秒杀逻辑如下,判断用户是否已经抢购过该商品,如果没有则查询待秒杀商品详情,判断该商品是否可以被秒杀,判断依据为库存是否足够

如果符合条件,则该商品库存减1,接着,再一次判断扣减是否成功,如果扣减成功则生成秒杀成功的订单,同时通知用户秒杀成功的信息。

public Boolean killItem(Integer killId, Integer userId) throws Exception {
    Boolean result=false;
 
    //TODO:判断当前用户是否已经抢购过当前商品
    if (itemKillSuccessMapper.countByKillUserId(killId,userId) <= 0){
      //TODO:查询待秒杀商品详情
      ItemKill itemKill=itemKillMapper.selectById(killId);
 
      //TODO:判断是否可以被秒杀canKill=1?
      if (itemKill!=null && 1==itemKill.getCanKill() ){
        //TODO:扣减库存-减一
        int res=itemKillMapper.updateKillItem(killId);
 
        //TODO:扣减是否成功?是-生成秒杀成功的订单,同时通知用户秒杀成功的消息
        if (res>0){
          commonRecordKillSuccessInfo(itemKill,userId);
 
          result=true;
        }
      }
    }else{
      throw new Exception("您已经抢购过该商品了!");
    }
    return result;
  }

使用redis的分布式锁,使用当前秒杀商品的id和当前用户的id组成一个key,使用StringBuffer拼接,使用雪花算法生成一个value,存进redis中。

@Autowired
  private StringRedisTemplate stringRedisTemplate;
  /**
   * 商品秒杀核心业务逻辑的处理-redis的分布式锁
   * @param killId
   * @param userId
   * @return
   * @throws Exception
   */
  @Override
  public Boolean killItemV3(Integer killId, Integer userId) throws Exception {
    Boolean result=false;
 
    if (itemKillSuccessMapper.countByKillUserId(killId,userId) <= 0){
 
      //TODO:借助Redis的原子操作实现分布式锁-对共享操作-资源进行控制
      ValueOperations valueOperations=stringRedisTemplate.opsForValue();
      final String key=new StringBuffer().append(killId).append(userId).append("-RedisLock").toString();
      final String value=RandomUtil.generateOrderCode();
      Boolean cacheRes=valueOperations.setIfAbsent(key,value); //luna脚本提供“分布式锁服务”,就可以写在一起
      //TOOD:redis部署节点宕机了
      if (cacheRes){
        stringRedisTemplate.expire(key,30, TimeUnit.SECONDS);
 
        try {
          ItemKill itemKill=itemKillMapper.selectByIdV2(killId);
          if (itemKill!=null && 1==itemKill.getCanKill() && itemKill.getTotal()>0){
            int res=itemKillMapper.updateKillItemV2(killId);
            if (res>0){
              commonRecordKillSuccessInfo(itemKill,userId);
 
              result=true;
            }
          }
        }catch (Exception e){
          throw new Exception("还没到抢购日期、已过了抢购时间或已被抢购完毕!");
        }finally {
          if (value.equals(valueOperations.get(key).toString())){
            stringRedisTemplate.delete(key);
          }
        }
      }
    }else{
      throw new Exception("Redis-您已经抢购过该商品了!");
    }
    return result;
  }

解决超卖问题
库存量减为负数
解决方法:在sql语句上判断,只有库存量大于0才能更新成功;
一个用户发出了两个秒杀请求,出现一个用户秒杀到两个商品的情况
解决方法:将秒杀表的userId和GoodsId设为唯一索引,如果一个用户已经秒杀到了,再来一个请求插不进秒杀表而发生事务回滚。

Redis预减库存减少数据库访问

  1. 系统初始化时,就把商品库存数量加载到Redis中
  2. 收到请求,Redis预减库存,库存不足,直接返回,否则进入3
  3. 请求入队,立即返回排队中
  4. 请求出队,生成订单,减少库存
  5. 客户端轮询,是否秒杀成功
    客户端根据服务端返回的状态判断应该显示什么,如果为-1说明库存不足,秒杀失败。如果为0说明秒杀成功但是还在排队中,如果是orderId则说明秒杀成功,用户是否要查看订单。如果要查看订单则通过orderId取数据库中查询相应订单并跳转到订单详情页。

项目中出现的问题

pom依赖的版本问题
mybatis的xml和接口的对应问题
redis的连接失败问题
封装了redis处理键值对的接口,开始在处理过程中使用了JDK1.8的新特性try()语句获得连接,问题出现在如果在try中捕获到异常,此时连接还没有关闭处于异常等待状态,出现了poolMaxIdle不够用的问题。
解决方法:捕获异常后应该在finally块中关闭连接;
压测过程中的redis Timeout异常
redis配置时

redis.timeout=10 //设置过小
redis.poolMaxTotal=1000 //设置过小
redis.poolMaxIdle=500 
redis.poolMaxWait=500

超时时间和最大连接数、最小活跃数都设置的太小,而并发量较大,导致处理IO速度较慢,超时时间变长。

rabbitMQ接收器监听异常
在接收器中将接收到的消息写入秒杀订单中,因为秒杀订单表设置了用户id和商品id的唯一索引,所以如果有重复的记录再写入会出现记录重复异常,由于没有捕获导致接收器监听失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值