zoukankan      html  css  js  c++  java
  • 阻止并发溢出

    <?php
    class Transaction {
        // 数据库连接对象
        public $link = null;
        function __construct() {
            $this->link = mysqli_connect ( '192.168.1.222', 'wedai', 'wedai', 'test' );
            mysqli_query ( $this->link, "set names 'UTF-8'" );
            mysqli_query ( $this->link, 'START TRANSACTION' );
        }
        
        // 并发测试
        function concurrent() {
            mysqli_query ( $this->link, "set session transaction isolation level read uncommitted" );
            // 设定延迟,单位微秒,1微秒等于百万分之一秒
            usleep ( rand ( 50, 500 ) );
            // 先查询一次
            $que = $this->selt1 ();
            // 库存大于0时允许减1
            if ($que ['storage_num'] > 0) {
                // 增加条件 WHERE storage_num > 0
                $sql = "UPDATE t1 SET storage_num = storage_num - 1 WHERE storage_num > 0";
                mysqli_query ( $this->link, $sql );
                // 再次查询
                $que = $this->selt1 ();
                if ($que ['storage_num'] >= 0) {
                    mysqli_query ( $this->link, "COMMIT" );
                    echo "减1成功";
                } else {
                    mysqli_query ( $this->link, "ROLLBACK" );
                    echo "减1失败";
                }
            }
        }
        //查询返回一条id=1的数据
        function selt1() {
            $sql = "SELECT * FROM t1 WHERE id = 1";
            $que = mysqli_query ( $this->link, $sql );
            return mysqli_fetch_array ( $que );
        }
    }
    header ( 'Content-type: text/html; charset=utf-8' );
    $ransaction = new Transaction ();
    $ransaction->concurrent ();
    ?>
  • 相关阅读:
    关于SOA和AOP
    网络通信
    网络层ddos与应用层ddos区别
    python 模块发布及使用
    安全等级划分依据与应急响应流程
    ssl与ssh
    列表计数及插入
    博客首语
    聊聊当今市面上的国产耳机
    “互联网+”背景下使用微信公众号增强班主任工作与整合教学资源(泰微课)
  • 原文地址:https://www.cnblogs.com/dreamhome/p/4529023.html
Copyright © 2011-2022 走看看