In the snapping scene, make sure two points:
1. Inventory will not be reduced/less sold
2. Speed of execution on 1 basis
I tested two scenarios,
Programme I. MySQL Open transaction
I simply designed the inventory table as follows
CREATE TABLE ' La_store ' ( int(notNULL ,int( 255notNULL, PRIMARYKEY (' id ')) ENGINE =DEFAULT CHARSET=utf8mb4;
Assuming 100,000 items in stock (val=100000)
PHP Logic Code
<?PHP$stime=Microtime(true);$count=100000;//Number of tests while($count>0){$count-=1;$con=mysql_connect("localhost", "User", "pwd");if(!$con) { die(' Could not connect: '.Mysql_error()); }mysql_select_db("database_name",$con);mysql_query(' Begin ');$record=mysql_query("SELECT * from La_store where id = 1 for update");//Get exclusive lock$record=Mysql_fetch_array($record);if($record[' Val ']>0) {//determine if there is stock//inventory logic$res=mysql_query("UPDATE la_test SET val = val-1 WHERE id=1");//Update Inventory}else{
No inventory logic.
}mysql_query("Commit");Mysql_close($con);}$etime=Microtime(true);//gets the time that the program execution ended$total=$etime-$stime;Echo $total;
Scenario two: Using Redis to open transactions
Assume 100,000 items in stock (set store 100000)
<?PHP$stime=Microtime(true);//Start Time$count=100000;//Number of tests while($count>0){$count-=1;$redis=NewRedis (); $redis->connect (' 127.0.0.1 ', 6379);$res=$redis->multi ()->decr (' Store ')->get (' Store ')exec();if($res[1]>0){ //In StockLogic}Else{ //No inventory logic}}$etime=Microtime(true);//gets the time that the program execution endedPrint_r($res);$total=$etime-$stime;Echo $total;
Test results:
Respectively, after 100,000 cycles, Redis spents 22 seconds, MySQL spents 50 seconds;
Redis can be used faster, but Redis transactions cannot be rolled back, and Redis is recommended if the business logic fails to roll back and the probability of a rollback is small. If the logic goes wrong, you have to roll back or use MySQL more safely.
Snapping logic with MySQL and Redis design