高并发库存操作

方式一: for update 用时5504
select * from PPTEST.TBL_SHOP mm where ID=#{id,jdbcType=VARCHAR} for update
select for update这是数据库行锁,也是我们常用的悲观锁,可用于针对某商品的秒杀操作,但是当出现主键索引和非主键索引同时等待对方时,会造成数据库死锁

方式二:加锁 用时9650
@Override
public void updateShop(String id,Integer num) {
try {
lock.lock();
ShopEntity entity = shopDao.getShop(id);
System.out.println("原数量是"+entity.getNum()+"我将对原数量减去" + num);
shopDao.updateShop(id,num);
entity = shopDao.getShop(id);
System.out.println("更新后的数量是"+entity.getNum());
}finally{
lock.unlock();
}
}

方式三:阻塞队列 耗时2184
请求过来的时候放到固定大小的阻塞队列,请求结束后或者秒杀时间结束后,遍历队列,做减操作,这需要显示购买数量,因为100个请求不等于100个库存
public void updateShop(String id,Integer num) {
ShopVO shopVO = new ShopVO();
shopVO.setNum(1);
shopVO.setId("1");
try {
queue.add(shopVO);
}catch (Exception e) {
System.out.println("该商品已经秒杀结束了奥!");
}
}

秒杀结束后执行的方法:
public void realUpdateShop() throws InterruptedException {
while(!queue.isEmpty()) {
ShopVO vo = queue.take();
System.out.println(vo.getNum());
shopDao.updateShop(vo.getId(),vo.getNum());
}
}

4.

  1. beginTranse(开启事务)  
  2. try{  
  3.     //quantity为请求减掉的库存数量  
  4.     $dbca->query('update s_store set amount = amount - quantity where postID = 12345');  
  5.     $result = $dbca->query('select amount from s_store where postID = 12345');  
  6.     if(result->amount < 0){  
  7.        throw new Exception('库存不足');  
  8.     }  
  9. }catch($e Exception){  
  10.     rollBack(回滚)  
  11. }  
  12. commit(提交事务)  


5.

  1. beginTranse(开启事务)  
  2. try{  
  3.     //quantity为请求减掉的库存数量  
  4.     $dbca->query('update s_store set amount = amount - quantity where amount>=quantity and postID = 12345');  
  5. }catch($e Exception){  
  6.     rollBack(回滚)  
  7. }  
  8. commit(提交事务)  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值