首頁 > php框架 > Swoole > 主體

這次我用swoole實現訂單延時,還原庫存!

發布: 2021-07-30 14:09:26
轉載
2786 人瀏覽過

這次我用swoole實現訂單延時,還原庫存!

一、業務場景:當客戶下單在指定的時間內如果沒有付款,那我們需要將這筆訂單取消掉,例如好的處理方法是運用延時取消,很多人首先想到的當然是crontab,這個也行,不過這裡我們運用swoole的異步毫秒定時器來實現,同樣也不會影響到當前程式的運作。

二、說明,order_status為1時代表客戶下單確定,為2時代表客戶已付款,為0時代表訂單已取消(正是swoole來做的)

三、舉例說明,庫存表csdn_product_stock產品ID為1的產品庫存數量為20,產品ID為2的庫存數量為40,然後客戶下單一筆產品ID1減10,產品ID2減20,所以庫存表只夠2次下單,例子中10秒後自動還原庫存。

如下圖,圖解:

1、第一次下完單產品ID1庫存從20減到了10,產品ID2庫存從40減到了20;2、第二次下完單產品ID的庫存為0了,產品ID2的庫存也為0了,

3、第三次下單時,程式提示Out of stock;

4、過了10秒鐘(每個訂單下單後往後推10秒),客戶兩次下單,由於沒有付款(csdn_order表的order_status為1),產品1和產品2的庫存被還原了(csdn_order表的order_status變為0),客戶又可以繼續下單了

這次我用swoole實現訂單延時,還原庫存!

1、所需要sql資料庫表

DROP TABLE IF EXISTS `csdn_order`;
CREATE TABLE `csdn_order` (
  `order_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `order_amount` float(10,2) unsigned NOT NULL DEFAULT '0.00',
  `user_name` varchar(64) CHARACTER SET latin1 NOT NULL DEFAULT '',
  `order_status` tinyint(2) unsigned NOT NULL DEFAULT '0',
  `date_created` datetime NOT NULL,
  PRIMARY KEY (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `csdn_order_detail`;
CREATE TABLE `csdn_order_detail` (
  `detail_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(10) unsigned NOT NULL,
  `product_id` int(10) NOT NULL,
  `product_price` float(10,2) NOT NULL,
  `product_number` smallint(4) unsigned NOT NULL DEFAULT '0',
  `date_created` datetime NOT NULL,
  PRIMARY KEY (`detail_id`),
  KEY `idx_order_id` (`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `csdn_product_stock`;
CREATE TABLE `csdn_product_stock` (
  `auto_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` int(10) NOT NULL,
  `product_stock_number` int(10) unsigned NOT NULL,
  `date_modified` datetime NOT NULL,
  PRIMARY KEY (`auto_id`),
  KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `csdn_product_stock` VALUES ('1', '1', '20', '2018-09-13 19:36:19');
INSERT INTO `csdn_product_stock` VALUES ('2', '2', '40', '2018-09-13 19:36:19');
登入後複製

下面貼出來純手工PHP,很多同學用了原生PHP,就不會運用到框架裡去,其實都一樣的,不要想得那麼複雜就是了。只要一點就是你用多了,你就會這樣覺得咯。

設定檔config.php  ,這個在框架的話,基本上都是配置好了。

<?php
$dbHost = "192.168.23.110";
$dbUser = "root";
$dbPassword = "123456";
$dbName = "test";
?>
登入後複製

swoole都是用在linux系統裡的,這裡的host你可以自己搭建虛擬主機,也可以上網購買屬於自己的伺服器

訂單提交的檔案order_submit.php,這裡對訂單生成,同時扣除庫存的一系列操作

<?php
require("config.php");
try {
    $pdo = new PDO("mysql:host=" . $dbHost . ";dbname=" . $dbName, $dbUser, $dbPassword, array(PDO::ATTR_PERSISTENT => true));
    $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $orderInfo = array(
        &#39;order_amount&#39; => 10.92,
        &#39;user_name&#39; => &#39;yusan&#39;,
        &#39;order_status&#39; => 1,
        &#39;date_created&#39; => &#39;now()&#39;,
        &#39;product_lit&#39; => array(
            0 => array(
                &#39;product_id&#39; => 1,
                &#39;product_price&#39; => 5.00,
                &#39;product_number&#39; => 10,
                &#39;date_created&#39; => &#39;now()&#39;
            ),
            1 => array(
                &#39;product_id&#39; => 2,
                &#39;product_price&#39; => 5.92,
                &#39;product_number&#39; => 20,
                &#39;date_created&#39; => &#39;now()&#39;
            )
        )
    );
    try{
        $pdo->beginTransaction();//开启事务处理
        $sql = &#39;insert into csdn_order (order_amount, user_name, order_status, date_created) values (:orderAmount, :userName, :orderStatus, now())&#39;;
        $stmt = $pdo->prepare($sql);  
        $affectedRows = $stmt->execute(array(&#39;:orderAmount&#39; => $orderInfo[&#39;order_amount&#39;], &#39;:userName&#39; => $orderInfo[&#39;user_name&#39;], &#39;:orderStatus&#39; => $orderInfo[&#39;order_status&#39;]));
        $orderId = $pdo->lastInsertId();
        if(!$affectedRows) {
            throw new PDOException("Failure to submit order!");
        }
        foreach($orderInfo[&#39;product_lit&#39;] as $productInfo) {
            $sqlProductDetail = &#39;insert into csdn_order_detail (order_id, product_id, product_price, product_number, date_created) values (:orderId, :productId, :productPrice, :productNumber, now())&#39;;
            $stmtProductDetail = $pdo->prepare($sqlProductDetail);  
            $stmtProductDetail->execute(array(&#39;:orderId&#39; => $orderId, &#39;:productId&#39; =>  $productInfo[&#39;product_id&#39;], &#39;:productPrice&#39; => $productInfo[&#39;product_price&#39;], &#39;:productNumber&#39; => $productInfo[&#39;product_number&#39;]));
            $sqlCheck = "select product_stock_number from csdn_product_stock where product_id=:productId";  
            $stmtCheck = $pdo->prepare($sqlCheck);  
            $stmtCheck->execute(array(&#39;:productId&#39; => $productInfo[&#39;product_id&#39;]));  
            $rowCheck = $stmtCheck->fetch(PDO::FETCH_ASSOC);
            if($rowCheck[&#39;product_stock_number&#39;] < $productInfo[&#39;product_number&#39;]) {
                throw new PDOException("Out of stock, Failure to submit order!");
            }
            $sqlProductStock = &#39;update csdn_product_stock set product_stock_number=product_stock_number-:productNumber, date_modified=now() where product_id=:productId&#39;;
            $stmtProductStock = $pdo->prepare($sqlProductStock);  
            $stmtProductStock->execute(array(&#39;:productNumber&#39; => $productInfo[&#39;product_number&#39;], &#39;:productId&#39; => $productInfo[&#39;product_id&#39;]));
            $affectedRowsProductStock = $stmtProductStock->rowCount();
            //库存没有正常扣除,失败,库存表里的product_stock_number设置了为非负数
            //如果库存不足时,sql异常:SQLSTATE[22003]: Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in &#39;(`test`.`csdn_product_stock`.`product_stock_number` - 20)&#39;
            if($affectedRowsProductStock <= 0) {
                throw new PDOException("Out of stock, Failure to submit order!");
            }
        }
        echo "Successful, Order Id is:" . $orderId .",Order Amount is:" . $orderInfo[&#39;order_amount&#39;] . "。";
        $pdo->commit();//提交事务
        //exec("php order_cancel.php -a" . $orderId . " &");
        pclose(popen(&#39;php order_cancel.php -a &#39; . $orderId . &#39; &&#39;, &#39;w&#39;));
        //system("php order_cancel.php -a" . $orderId . " &", $phpResult);
        //echo $phpResult;
    }catch(PDOException $e){
        echo $e->getMessage();
        $pdo->rollback();
    }
    $pdo = null;
} catch (PDOException $e) {
    echo $e->getMessage();
}
?>
登入後複製

訂單的延時處理order_cancel.php

<?php
require("config.php");
$queryString = getopt(&#39;a:&#39;);
$userParams = array($queryString);
appendLog(date("Y-m-d H:i:s") . "\t" . $queryString[&#39;a&#39;] . "\t" . "start");
try {
    $pdo = new PDO("mysql:host=" . $dbHost . ";dbname=" . $dbName, $dbUser, $dbPassword, array(PDO::ATTR_PERSISTENT => true));
    $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    swoole_timer_after(10000, function ($queryString) {
        global $queryString, $pdo;
        try{
            $pdo->beginTransaction();//开启事务处理
            $orderId = $queryString[&#39;a&#39;];  
            $sql = "select order_status from csdn_order where order_id=:orderId";  
            $stmt = $pdo->prepare($sql);  
            $stmt->execute(array(&#39;:orderId&#39; => $orderId));  
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            //$row[&#39;order_status&#39;] === "1"代表已下单,但未付款,我们还原库存只针对未付款的订单
            if(isset($row[&#39;order_status&#39;]) && $row[&#39;order_status&#39;] === "1") {
                $sqlOrderDetail = "select product_id, product_number from csdn_order_detail where order_id=:orderId";  
                $stmtOrderDetail = $pdo->prepare($sqlOrderDetail);  
                $stmtOrderDetail->execute(array(&#39;:orderId&#39; => $orderId));  
                while($rowOrderDetail = $stmtOrderDetail->fetch(PDO::FETCH_ASSOC)) {
                    $sqlRestoreStock = "update csdn_product_stock set product_stock_number=product_stock_number + :productNumber, date_modified=now() where product_id=:productId";  
                    $stmtRestoreStock = $pdo->prepare($sqlRestoreStock);
                    $stmtRestoreStock->execute(array(&#39;:productNumber&#39; => $rowOrderDetail[&#39;product_number&#39;], &#39;:productId&#39; => $rowOrderDetail[&#39;product_id&#39;]));
                }
                $sqlRestoreOrder = "update csdn_order set order_status=:orderStatus where order_id=:orderId";  
                $stmtRestoreOrder = $pdo->prepare($sqlRestoreOrder);
                $stmtRestoreOrder->execute(array(&#39;:orderStatus&#39; => 0, &#39;:orderId&#39; => $orderId));
            }
            $pdo->commit();//提交事务
        }catch(PDOException $e){
            echo $e->getMessage();
            $pdo->rollback();
        }
        $pdo = null;
        appendLog(date("Y-m-d H:i:s") . "\t" . $queryString[&#39;a&#39;] . "\t" . "end\t" . json_encode($queryString));
    }, $pdo);
} catch (PDOException $e) {
    echo $e->getMessage();
}
function appendLog($str) {
    $dir = &#39;log.txt&#39;;
    $fh = fopen($dir, "a");
    fwrite($fh, $str . "\n");
    fclose($fh);
}
?>
登入後複製

更多swoole技術文章,請訪問swoole教程專欄!

以上是這次我用swoole實現訂單延時,還原庫存!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:磊丰
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板