이번에는 주문을 지연하고 재고를 복원하기 위해 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이 됨), 고객은 계속 주문할 수 있습니다
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( 'order_amount' => 10.92, 'user_name' => 'yusan', 'order_status' => 1, 'date_created' => 'now()', 'product_lit' => array( 0 => array( 'product_id' => 1, 'product_price' => 5.00, 'product_number' => 10, 'date_created' => 'now()' ), 1 => array( 'product_id' => 2, 'product_price' => 5.92, 'product_number' => 20, 'date_created' => 'now()' ) ) ); try{ $pdo->beginTransaction();//开启事务处理 $sql = 'insert into csdn_order (order_amount, user_name, order_status, date_created) values (:orderAmount, :userName, :orderStatus, now())'; $stmt = $pdo->prepare($sql); $affectedRows = $stmt->execute(array(':orderAmount' => $orderInfo['order_amount'], ':userName' => $orderInfo['user_name'], ':orderStatus' => $orderInfo['order_status'])); $orderId = $pdo->lastInsertId(); if(!$affectedRows) { throw new PDOException("Failure to submit order!"); } foreach($orderInfo['product_lit'] as $productInfo) { $sqlProductDetail = 'insert into csdn_order_detail (order_id, product_id, product_price, product_number, date_created) values (:orderId, :productId, :productPrice, :productNumber, now())'; $stmtProductDetail = $pdo->prepare($sqlProductDetail); $stmtProductDetail->execute(array(':orderId' => $orderId, ':productId' => $productInfo['product_id'], ':productPrice' => $productInfo['product_price'], ':productNumber' => $productInfo['product_number'])); $sqlCheck = "select product_stock_number from csdn_product_stock where product_id=:productId"; $stmtCheck = $pdo->prepare($sqlCheck); $stmtCheck->execute(array(':productId' => $productInfo['product_id'])); $rowCheck = $stmtCheck->fetch(PDO::FETCH_ASSOC); if($rowCheck['product_stock_number'] < $productInfo['product_number']) { throw new PDOException("Out of stock, Failure to submit order!"); } $sqlProductStock = 'update csdn_product_stock set product_stock_number=product_stock_number-:productNumber, date_modified=now() where product_id=:productId'; $stmtProductStock = $pdo->prepare($sqlProductStock); $stmtProductStock->execute(array(':productNumber' => $productInfo['product_number'], ':productId' => $productInfo['product_id'])); $affectedRowsProductStock = $stmtProductStock->rowCount(); //库存没有正常扣除,失败,库存表里的product_stock_number设置了为非负数 //如果库存不足时,sql异常:SQLSTATE[22003]: Numeric value out of range: 1690 BIGINT UNSIGNED value is out of range in '(`test`.`csdn_product_stock`.`product_stock_number` - 20)' if($affectedRowsProductStock <= 0) { throw new PDOException("Out of stock, Failure to submit order!"); } } echo "Successful, Order Id is:" . $orderId .",Order Amount is:" . $orderInfo['order_amount'] . "。"; $pdo->commit();//提交事务 //exec("php order_cancel.php -a" . $orderId . " &"); pclose(popen('php order_cancel.php -a ' . $orderId . ' &', 'w')); //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('a:'); $userParams = array($queryString); appendLog(date("Y-m-d H:i:s") . "\t" . $queryString['a'] . "\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['a']; $sql = "select order_status from csdn_order where order_id=:orderId"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':orderId' => $orderId)); $row = $stmt->fetch(PDO::FETCH_ASSOC); //$row['order_status'] === "1"代表已下单,但未付款,我们还原库存只针对未付款的订单 if(isset($row['order_status']) && $row['order_status'] === "1") { $sqlOrderDetail = "select product_id, product_number from csdn_order_detail where order_id=:orderId"; $stmtOrderDetail = $pdo->prepare($sqlOrderDetail); $stmtOrderDetail->execute(array(':orderId' => $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(':productNumber' => $rowOrderDetail['product_number'], ':productId' => $rowOrderDetail['product_id'])); } $sqlRestoreOrder = "update csdn_order set order_status=:orderStatus where order_id=:orderId"; $stmtRestoreOrder = $pdo->prepare($sqlRestoreOrder); $stmtRestoreOrder->execute(array(':orderStatus' => 0, ':orderId' => $orderId)); } $pdo->commit();//提交事务 }catch(PDOException $e){ echo $e->getMessage(); $pdo->rollback(); } $pdo = null; appendLog(date("Y-m-d H:i:s") . "\t" . $queryString['a'] . "\t" . "end\t" . json_encode($queryString)); }, $pdo); } catch (PDOException $e) { echo $e->getMessage(); } function appendLog($str) { $dir = 'log.txt'; $fh = fopen($dir, "a"); fwrite($fh, $str . "\n"); fclose($fh); } ?>
더 많은 swoole 기술 기사를 보려면 swoole tutorial 칼럼을 방문하세요!
위 내용은 이번에는 주문을 지연하고 재고를 복원하기 위해 Swoole을 사용했습니다!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

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

뜨거운 주제











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

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

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

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

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

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

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

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