秒杀系统并发情况下解决超卖问题

非分布式秒杀系统 并发情况下解决超卖问题

乐观锁防止超卖 / 令牌桶限流/ redis缓存 /接口限流/接口加盐/单用户限制访问频率/消息队列异步处理订单

#数据库表

drop table if exists `stock`;
create table `stock`(
	`id` int(11) unsigned not null auto_increment,
	`name` varchar(50) not null default '' comment '名称',
	`count` int(11) not null comment '库存',
	`sale` int(11) not null comment '已售',
	`version` int(11) not null comment '乐观锁,版本号',
	primary key(`id`)
)engine=innoDB default charset=utf8;

drop table if exists `stock_order`;
create table `stock_order`(
	`id` int(11) unsigned not null auto_increment,
	`sid` int(11) not null comment '库存id',
	`name` varchar(30) not null default '' comment '商品名称',
	`create_time` timestamp not null default current_timestamp on update current_timestamp comment '创建时间',
	primary key(`id`)
)engine=innoDB default charset=utf8;


server.port=8080
server.servlet.context-path=/

#数据库源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ms?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

logging.level.root=info
logging.level.com.nmsl.dao=debug

#mybatis配置
mybatis.mapper-locations=classpath:com/nmsl/mapper/*.xml
mybatis.type-aliases-package=com.nmsl.entity

1.悲观锁

@RestController
public class StockController {
   

    @Resource
    private OrderService orderService;

    @GetMapping("/kill")
    public String kill(Integer id){
       //秒杀方法
        System.out.println("秒杀商品的id = " + id);
        //根据秒杀商品的id去调用秒杀业务
        try {
   
            synchronized (this){
   
                //放在控制器调用的地方使用synchronized
                int orderId = orderService.kill(id);
                return "秒杀成功,订单id为 = " + String.valueOf(orderId);
            }

        } catch (Exception e) {
   
            e.printStackTrace();
            return e.getMessage();
        }
    }


    
    
    
/**
 * @author Paracosm
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
   

    @Resource
    private StockDao stockDao;

    @Resource
    private OrderDao orderDao;

    
    //synchronized最好不要加在方法上,而是加在controller调用该方法的地方.
    //如果要加在方法上必须去掉事务注解@Transactional.
    //因为该方法还是被包含在事务内的, 事务并没有完成,还是有可能出现多提交的问题. 所以需要取消事务注解.
    //public synchronized int kill(Integer id) {   
    
    @Override
    public  int kill(Integer id) {
      
        //1.根据商品id校验库存
        Stock stock = checkStock(id);

        //2.扣除库存
        updateSale(stock);

        //3.创建订单
        return createOrder(stock);
    }

    //1.校验库存
    private Stock checkStock (Integer id){
   
        Stock stock = stockDao.checkStock(id);;
        if (stock.getSale().equals(stock.getCount())){
   
            throw new RuntimeException("库存不足");
        }
        return stock;
    }

    //2.扣除库存
    private void updateSale(Stock stock){
   
        stock.setSale(stock.getSale() + 1);
        stockDao.updateSale(stock);
    }
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值