فهرست منبع

doDecrAndCreateOrder 方法中 事务代码完全放入锁代码块里

dinglan 2 سال پیش
والد
کامیت
2a9048b8e0

+ 1 - 1
src/main/java/com/sw/controller/SnatchMaskController.java

@@ -32,7 +32,7 @@ public class SnatchMaskController {
             if (redisTemplate.opsForSet().isMember("successUserUids", uid)) {
                 return "你已经抢到口罩了";
             } else {
-                return snatchMaskService.doSnatch(uid);
+                return snatchMaskService.doSnatch(uid, 1);
             }
         } else {
             return "非法输入";

+ 1 - 1
src/main/java/com/sw/service/SnatchMaskService.java

@@ -6,7 +6,7 @@ package com.sw.service;
  * @Date 2022/2/18 13:21
  **/
 public interface SnatchMaskService {
-    String doSnatch(Integer uid);
+    String doSnatch(Integer uid, Integer maskId);
 
     Boolean checkAndDecrRemaining(Integer mid);
 

+ 2 - 18
src/main/java/com/sw/service/impl/SnatchMaskServiceImpl.java

@@ -53,8 +53,7 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
 
     @Override
     @Transactional
-    public String doSnatch(Integer uid) {
-        Integer maskId = 1;
+    public String doSnatch(Integer uid, Integer maskId) {
         //1.get the amount of remaining masks
         TMask mask = maskService.getById(maskId);
         if (mask.getMaskStock() > amount) {
@@ -164,22 +163,7 @@ public class SnatchMaskServiceImpl implements SnatchMaskService {
         try {
             while (lock.tryLock(1000, TimeUnit.MILLISECONDS)) {
                 log.info("线程:{} 获取锁", threadName);
-                //1.get the amount of remaining masks
-                TMask mask = maskService.getById(maskId);
-                System.out.println(mask.getMaskStock() + "----" + Thread.currentThread());
-                if (mask.getMaskStock() >= amount) {
-                    //3.create order
-                    int res = orderService.creatOrder(uid, maskId);
-                    //4.decrease the stock of mask
-                    Boolean flag = maskService.decrease(maskId, mask.getMaskStock() - amount);
-                    if (res > 0 && flag) {
-                        //3. add to successUserUids
-                        redisTemplate.opsForSet().add("successUserUids", uid);
-                    }
-                } else {
-                    // TODO 如果sql中库存不够 扣减失败之后 消息已经消费了 或者是事物回滚了  如何处理???
-                    return;
-                }
+                log.info("doSnatch方法执行结果:{}", this.doSnatch(uid, maskId));
                 lock.unlock();
                 log.info("{}:业务执行完成", threadName);
                 break;