非分布式秒杀系统 并发情况下解决超卖问题
乐观锁防止超卖 / 令牌桶限流/ 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);
}