本系统流程图如下
1.超卖
1.1超卖背景
很多小伙伴可能觉得,我秒杀项目中的库存一个一个减,为什么会造成超卖呢?
当然,如果你是单线程的小系统当然不需要担心任何问题,但秒杀项目的特点是短时间内的超高并发,一堆用户去冲击很少量的商品库存,系统当然会反应不过来是谁买走了真正的库存商品,超卖情况也就随之发生,下面我们用代码详细展示一下!
1.2.情景再现
新建一个spring web项目,controller,dao,service层分别如下
Service层
package com.seckillsample.demo.service;
import com.seckillsample.demo.dao.SKDao;
import org.springframework.stereotype.Service;
@Service
public class SKService {
private SKDao skDao = new SKDao();
public void processSecKill() {
Integer count = skDao.getCount();
if (count > 0) {
System.out.println("恭喜您,抢购成功!");
count--;
skDao.updateCount(count);
} else {
System.out.println("抱歉,已经卖完了");
}
}
}
Dao层
package com.seckillsample.demo.dao;
public class SKDao {
public static Integer count = 10;
public Integer getCount() {
return SKDao.count;
}
public void updateCount(Integer count) {
SKDao.count = count;
}
}
Controller层
package com.seckillsample.demo.controller;
import com.seckillsample.demo.service.SKService;
import javafx.scene.control.Skin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class SKController {
@Resource
private SKService skService;
@ResponseBody
@RequestMapping("/seckill")
public String doSeckill() {
skService