乐观锁解决库存超卖问题

2023-11-27 07:01

本文主要是介绍乐观锁解决库存超卖问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

public BaseResult creatOneOrder(FlightOrderServiceImpl orderService, List<Map<String, String>> passengers,Map<String, String> selectFlightMap,String account) throws Exception {//如果是单程//判断座位数是否>=1//是的话就直接减库存//不是就return 201,库存不够int k=0;FlightSeat seat = seatService.getById(selectFlightMap.get("seatId"));if(seat.getRestNum()<1){return new BaseResult(201,"库存不够了");}seat.setRestNum(seat.getRestNum()-1);boolean updateResult = seatService.updateById(seat);if(!updateResult){//如果更新失败//说明在更新前有其他人已经对该行剩余量进行了修改//就再试一次,先判断库存int maxRetries = 5; //最大重试次数int retryCount = 0;while (retryCount < maxRetries) {// 获取最新的座位信息FlightSeat updatedSeat = seatService.getById(selectFlightMap.get("seatId"));// 检查座位是否仍然可用if (updatedSeat.getRestNum() < 1) {return new BaseResult(201, "库存不够了");}// 尝试更新座位信息updatedSeat.setRestNum(updatedSeat.getRestNum() - 1);boolean retryUpdateResult = seatService.updateById(updatedSeat);// 检查更新操作的结果if (retryUpdateResult) {// 成功更新,生成订单,跳出循环k=1;break;} else {// 增加重试计数并进行下一次尝试retryCount++;}if (retryCount == maxRetries) {return new BaseResult(202, "更新失败,重试次数已达上限");}}}else {k =1;}if(k==1){//k=1说明库存成功减少了FlightOrder Order = new FlightOrder();// 获取当前时间LocalDateTime currentTime = LocalDateTime.now();// 如果你想以特定格式输出当前时间,可以使用 DateTimeFormatterDateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formattedCurrentTime = currentTime.format(formatter);Order.setDate(formattedCurrentTime);// 设置超时时间为当前时间的15分钟后LocalDateTime timeoutTime = currentTime.plusMinutes(15);String formattedTimeoutTime = timeoutTime.format(formatter);Order.setTimeout(formattedTimeoutTime);Order.setOrderId(String.valueOf(new SnowUtil(0,0).getId()));//                redisTemplate.opsForValue().set(Order.getOrderId(), Order.getOrderId(), 15, TimeUnit.MINUTES);redisTemplate.opsForValue().set(Order.getOrderId(), Order.getOrderId(), 15, TimeUnit.MINUTES);Flight flight = new Flight();flight = flightService.getById(selectFlightMap.get("flightId"));Order.setFlightCode(flight.getFlightCode());Order.setStage("待支付");Order.setWay("单程");Order.setUserId(account);Air air = airService.getById(flight.getAirId());Order.setPrice(seat.getPrice());Order.setAllPrice(seat.getPrice());Order.setSeatType(seat.getSeatType());Order.setDepCity(flight.getDepCity());Order.setDepDate(flight.getDepDate());Order.setDepTime(flight.getDepTime());Order.setArrCity(flight.getArrCity());Order.setArrDate(flight.getArrDate());Order.setArrTime(flight.getArrTime());Order.setDepAirport(flight.getDepAirport());Order.setArrAirport(flight.getArrAirport());Order.setAirlineName(flight.getAirlineName());Order.setAirType(air.getType());orderService.save(Order);for (Map<String, String> pas : passengers) {FlightPassenger passenger = new FlightPassenger();passenger.setOrderId(Order.getOrderId());passenger.setName(pas.get("name"));passenger.setIdentityId(pas.get("sfz"));passenger.setPhone(pas.get("phone"));passengerService.save(passenger);}return new BaseResult(200,"支付成功",Order.getOrderId());}else return new BaseResult(202,"库存不够或者重试次数达到上限");}

往返票

 @Transactionalpublic BaseResult creatTwoOrder(FlightOrderServiceImpl orderService,List<Map<String, String>> passengers,Map<String, String> selectFlightMap,String account) throws Exception {//            座位int k1=0,k2=0;FlightSeat seat = seatService.getById(selectFlightMap.get("goSeatId"));FlightSeat seatback = seatService.getById(selectFlightMap.get("backSeatId"));//先判断库存if(seat.getRestNum()<1||seatback.getRestNum()<1){return new BaseResult(201,"库存不够了");}//如果库存都够seat.setRestNum(seat.getRestNum()-1);boolean updateResult = seatService.updateById(seat);if(!updateResult){//如果更新失败int max =5;int cnt=0;while(cnt<max){//先判断库存FlightSeat newSeat = seatService.getById(selectFlightMap.get("goSeatId"));if(newSeat.getRestNum()<1){return new BaseResult(201,"库存不够了");}//如果库存足够newSeat.setRestNum(newSeat.getRestNum()-1);boolean updateSeatResult = seatService.updateById(newSeat);if(updateSeatResult){//成功k1 =1;break;}else {//修改库存又失败了,有其他线程已经将这行记录的值进行了修改cnt++;}if(cnt==max){return new BaseResult(202,"重试次数已经达到上限");}}}else {//一次成功k1 =1;}//到这里的话就说明去程的票减库存已经成功了//开始买返程的票seatback.setRestNum(seatback.getRestNum()-1);boolean backSeatResult = seatService.updateById(seatback);if(!backSeatResult){//如果更新失败int max1 =5;int cnt1 =0;while (cnt1<max1){FlightSeat newSeatback = seatService.getById(selectFlightMap.get("backSeatId"));if(newSeatback.getRestNum()<1){//回滚去程的票数TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();return new BaseResult(202,"库存不够了");}//如果库存足够boolean result = seatService.updateById(newSeatback);if(result){k2=1;break;}else {cnt1++;}if(cnt1==max1){//首先要回滚去程的库存TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();return new BaseResult(202,"达到尝试上限");}}}else {k2=1;}if(k1==1&&k2==1){FlightOrder Order = new FlightOrder();// 获取当前时间LocalDateTime currentTime = LocalDateTime.now();// 如果你想以特定格式输出当前时间,可以使用 DateTimeFormatterDateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formattedCurrentTime = currentTime.format(formatter);Order.setDate(formattedCurrentTime);// 设置超时时间为当前时间的15分钟后LocalDateTime timeoutTime = currentTime.plusMinutes(15);String formattedTimeoutTime = timeoutTime.format(formatter);Order.setTimeout(formattedTimeoutTime);Order.setOrderId(String.valueOf(new SnowUtil(0,0).getId()));redisTemplate.opsForValue().set(Order.getOrderId(), Order.getOrderId(), 15, TimeUnit.MINUTES);//            获取数据Flight flight1 = flightService.getById(selectFlightMap.get("goId"));Air air1 = airService.getById(flight1.getAirId());Order.setDepCity(flight1.getDepCity());Order.setDepDate(flight1.getDepDate());Order.setDepTime(flight1.getDepTime());Order.setArrCity(flight1.getArrCity());Order.setArrDate(flight1.getArrDate());Order.setArrTime(flight1.getArrTime());Order.setDepAirport(flight1.getDepAirport());Order.setArrAirport(flight1.getArrAirport());Order.setAirlineName(flight1.getAirlineName());Order.setAirType(air1.getType());//            订单对象Order.setFlightCode(flight1.getFlightCode());Order.setStage("待支付");Order.setWay("往返");Order.setUserId(account);Order.setPrice(seat.getPrice());Order.setSeatType(seat.getSeatType());Flight flight2 = flightService.getById(selectFlightMap.get("backId"));Air air2 = airService.getById(flight2.getAirId());Order.setBackDepCity(flight2.getDepCity());Order.setBackDepDate(flight2.getDepDate());Order.setBackDepTime(flight2.getDepTime());Order.setBackArrCity(flight2.getArrCity());Order.setBackArrDate(flight2.getArrDate());Order.setBackArrTime(flight2.getArrTime());Order.setBackDepAirport(flight2.getDepAirport());Order.setBackArrAirport(flight2.getArrAirport());Order.setBackAirlineName(flight2.getAirlineName());Order.setBackAirType(air2.getType());Order.setBackPrice(seatback.getPrice());Order.setAllPrice(seat.getPrice()+seatback.getPrice());Order.setBackFlightCode(flight2.getFlightCode());Order.setBackSeatType(seatback.getSeatType());orderService.save(Order);for (Map<String, String> pas : passengers) {FlightPassenger passenger = new FlightPassenger();passenger.setOrderId(Order.getOrderId());passenger.setName(pas.get("name"));passenger.setIdentityId(pas.get("sfz"));passenger.setPhone(pas.get("phone"));passengerService.save(passenger);}return new BaseResult(200,"支付成功",Order.getOrderId());}else {TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();return new BaseResult(202, "库存不够或者达到重试次数上限");}}

这篇关于乐观锁解决库存超卖问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/427239

相关文章

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Spring事务中@Transactional注解不生效的原因分析与解决

《Spring事务中@Transactional注解不生效的原因分析与解决》在Spring框架中,@Transactional注解是管理数据库事务的核心方式,本文将深入分析事务自调用的底层原理,解释为... 目录1. 引言2. 事务自调用问题重现2.1 示例代码2.2 问题现象3. 为什么事务自调用会失效3

mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)的解决方法

《mysql出现ERROR2003(HY000):Can‘tconnecttoMySQLserveron‘localhost‘(10061)的解决方法》本文主要介绍了mysql出现... 目录前言:第一步:第二步:第三步:总结:前言:当你想通过命令窗口想打开mysql时候发现提http://www.cpp

SpringBoot启动报错的11个高频问题排查与解决终极指南

《SpringBoot启动报错的11个高频问题排查与解决终极指南》这篇文章主要为大家详细介绍了SpringBoot启动报错的11个高频问题的排查与解决,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一... 目录1. 依赖冲突:NoSuchMethodError 的终极解法2. Bean注入失败:No qu

springboot报错Invalid bound statement (not found)的解决

《springboot报错Invalidboundstatement(notfound)的解决》本文主要介绍了springboot报错Invalidboundstatement(not... 目录一. 问题描述二.解决问题三. 添加配置项 四.其他的解决方案4.1 Mapper 接口与 XML 文件不匹配

MySQL新增字段后Java实体未更新的潜在问题与解决方案

《MySQL新增字段后Java实体未更新的潜在问题与解决方案》在Java+MySQL的开发中,我们通常使用ORM框架来映射数据库表与Java对象,但有时候,数据库表结构变更(如新增字段)后,开发人员可... 目录引言1. 问题背景:数据库与 Java 实体不同步1.1 常见场景1.2 示例代码2. 不同操作

Python中ModuleNotFoundError: No module named ‘timm’的错误解决

《Python中ModuleNotFoundError:Nomodulenamed‘timm’的错误解决》本文主要介绍了Python中ModuleNotFoundError:Nomodulen... 目录一、引言二、错误原因分析三、解决办法1.安装timm模块2. 检查python环境3. 解决安装路径问题

如何解决mysql出现Incorrect string value for column ‘表项‘ at row 1错误问题

《如何解决mysql出现Incorrectstringvalueforcolumn‘表项‘atrow1错误问题》:本文主要介绍如何解决mysql出现Incorrectstringv... 目录mysql出现Incorrect string value for column ‘表项‘ at row 1错误报错

如何解决Spring MVC中响应乱码问题

《如何解决SpringMVC中响应乱码问题》:本文主要介绍如何解决SpringMVC中响应乱码问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring MVC最新响应中乱码解决方式以前的解决办法这是比较通用的一种方法总结Spring MVC最新响应中乱码解

Java报NoClassDefFoundError异常的原因及解决

《Java报NoClassDefFoundError异常的原因及解决》在Java开发过程中,java.lang.NoClassDefFoundError是一个令人头疼的运行时错误,本文将深入探讨这一问... 目录一、问题分析二、报错原因三、解决思路四、常见场景及原因五、深入解决思路六、预http://www