PHP 프레임워크 Swoole 이번에는 주문을 지연하고 재고를 복원하기 위해 Swoole을 사용했습니다!

이번에는 주문을 지연하고 재고를 복원하기 위해 Swoole을 사용했습니다!

Jul 30, 2021 pm 02:09 PM
swoole

이번에는 주문을 지연하고 재고를 복원하기 위해 Swoole을 사용했습니다!

1. 비즈니스 시나리오: 고객이 주문을 하고 지정된 시간 내에 결제하지 않으면 주문을 취소해야 합니다. 예를 들어 지연 취소를 사용하는 것이 좋습니다. , 많은 사람들이 가장 먼저 생각하는 것은 Crontab입니다. 이것도 가능하지만 여기서는 swoole의 비동기 밀리초 타이머를 사용하여 구현하며 이는 현재 프로그램 실행에도 영향을 미치지 않습니다.

2. 설명, order_status가 1이면 주문이 완료되었음을 의미하고, 2이면 결제가 완료되었음을 의미하며, 0이면 주문이 취소되었음을 의미합니다(이것은 swoole이 하는 일입니다)

세 가지 예를 들어 재고 테이블 csdn_product_stock product 제품 ID 1의 재고 수량이 20이고, 제품 ID 2의 재고 수량이 40입니다. 그러면 고객이 주문하면 제품 ID1이 줄어듭니다. 10만큼, 제품 ID2는 20만큼 감소합니다. 따라서 재고 테이블은 2개의 주문에만 충분합니다. 예에서는 10초 후에 자동으로 재고를 복원합니다.

아래 그림과 같이

1. 처음 주문한 후 제품 ID1의 재고가 20개에서 10개로 줄었고, 제품 ID2의 재고도 40개에서 20개로 줄었습니다. 두 번째 주문 시 제품 ID의 재고는 0 이고, 제품 ID2의 재고도 0입니다.

3. 세 번째 주문 시 프로그램은

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 시스템에서 사용됩니다. 여기서 호스트용 가상 호스트를 구축하거나 온라인으로 자체 서버를 구입할 수 있습니다.

여기에서 주문 제출 파일 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 tutorial 칼럼을 방문하세요!

위 내용은 이번에는 주문을 지연하고 재고를 복원하기 위해 Swoole을 사용했습니다!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Laravel에서 Swoole 코루틴을 사용하는 방법 Laravel에서 Swoole 코루틴을 사용하는 방법 Apr 09, 2024 pm 06:48 PM

Laravel에서 Swoole 코루틴을 사용하면 많은 수의 요청을 동시에 처리할 수 있습니다. 장점은 다음과 같습니다. 동시 처리: 여러 요청을 동시에 처리할 수 있습니다. 고성능: Linux epoll 이벤트 메커니즘을 기반으로 요청을 효율적으로 처리합니다. 낮은 리소스 소비: 더 적은 서버 리소스가 필요합니다. 간편한 통합: Laravel 프레임워크와 원활하게 통합되어 사용이 간편합니다.

Swoole을 사용하여 고성능 HTTP 역방향 프록시 서버를 구현하는 방법 Swoole을 사용하여 고성능 HTTP 역방향 프록시 서버를 구현하는 방법 Nov 07, 2023 am 08:18 AM

Swoole을 사용하여 고성능 HTTP 역방향 프록시 서버를 구현하는 방법 Swoole은 PHP 언어를 기반으로 하는 고성능, 비동기식 동시 네트워크 통신 프레임워크입니다. 일련의 네트워크 기능을 제공하며 HTTP 서버, WebSocket 서버 등을 구현하는 데 사용할 수 있습니다. 이 기사에서는 Swoole을 사용하여 고성능 HTTP 역방향 프록시 서버를 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 환경 구성 먼저 서버에 Swoole 확장 프로그램을 설치해야 합니다.

스울과 워커맨 중 어느 것이 더 낫나요? 스울과 워커맨 중 어느 것이 더 낫나요? Apr 09, 2024 pm 07:00 PM

Swoole과 Workerman은 모두 고성능 PHP 서버 프레임워크입니다. 비동기 처리, 우수한 성능 및 확장성으로 잘 알려진 Swoole은 많은 수의 동시 요청과 높은 처리량을 처리해야 하는 프로젝트에 적합합니다. Workerman은 사용 편의성과 낮은 동시성 볼륨을 처리하는 프로젝트에 더 적합한 직관적인 API를 통해 비동기식 및 동기식 모드의 유연성을 제공합니다.

Swoole 프레임워크에서 서비스를 다시 시작하는 방법 Swoole 프레임워크에서 서비스를 다시 시작하는 방법 Apr 09, 2024 pm 06:15 PM

Swoole 서비스를 다시 시작하려면 다음 단계를 따르십시오. 서비스 상태를 확인하고 PID를 가져옵니다. 서비스를 중지하려면 "kill -15 PID"를 사용하십시오. 서비스를 시작하는 데 사용한 것과 동일한 명령을 사용하여 서비스를 다시 시작합니다.

swoole_process를 사용하면 사용자가 어떻게 전환할 수 있나요? swoole_process를 사용하면 사용자가 어떻게 전환할 수 있나요? Apr 09, 2024 pm 06:21 PM

Swoole 프로세스를 통해 사용자는 프로세스를 생성하고 프로세스를 시작할 수 있습니다.

Swoole 또는 Java 중 어느 것이 더 나은 성능을 가지고 있습니까? Swoole 또는 Java 중 어느 것이 더 나은 성능을 가지고 있습니까? Apr 09, 2024 pm 07:03 PM

성능 비교: 처리량: Swoole은 코루틴 메커니즘 덕분에 처리량이 더 높습니다. 대기 시간: Swoole의 코루틴 컨텍스트 전환은 오버헤드가 낮고 대기 시간이 더 짧습니다. 메모리 소비: Swoole의 코루틴은 더 적은 메모리를 차지합니다. 사용 용이성: Swoole은 사용하기 쉬운 동시 프로그래밍 API를 제공합니다.

Swoole의 실제 작동: 동시 작업 처리를 위해 코루틴을 사용하는 방법 Swoole의 실제 작동: 동시 작업 처리를 위해 코루틴을 사용하는 방법 Nov 07, 2023 pm 02:55 PM

Swoole의 실제 작동: 동시 작업 처리를 위해 코루틴을 사용하는 방법 소개 일상적인 개발에서 우리는 동시에 여러 작업을 처리해야 하는 상황에 자주 직면합니다. 전통적인 처리 방법은 다중 스레드 또는 다중 프로세스를 사용하여 동시 처리를 수행하는 것이지만 이 방법에는 성능 및 리소스 소비 측면에서 특정 문제가 있습니다. 스크립팅 언어로서 PHP는 일반적으로 작업을 처리하기 위해 다중 스레딩 또는 다중 프로세스 방법을 직접 사용할 수 없습니다. 그러나 Swoole 코루틴 라이브러리의 도움으로 코루틴을 사용하여 고성능 동시 작업 처리를 달성할 수 있습니다. 이 글에서 소개할

Swoole Advanced: 서버 CPU 활용도를 최적화하는 방법 Swoole Advanced: 서버 CPU 활용도를 최적화하는 방법 Nov 07, 2023 pm 12:27 PM

Swoole은 강력한 비동기 메커니즘과 이벤트 중심 기능을 갖춘 고성능 PHP 네트워크 개발 프레임워크로, 동시성 및 처리량이 높은 서버 애플리케이션을 신속하게 구축할 수 있습니다. 그러나 비즈니스가 지속적으로 확장되고 동시성 양이 증가함에 따라 서버의 CPU 사용률이 병목 현상을 일으키고 서버의 성능과 안정성에 영향을 미칠 수 있습니다. 따라서 본 글에서는 Swoole 서버의 성능과 안정성을 향상시키면서 서버의 CPU 활용도를 최적화하는 방법을 소개하고 구체적인 최적화 코드 예시를 제공하겠습니다. 하나,

See all articles