鍍金池/ 問答/數(shù)據(jù)庫/ mysql 排它鎖無效

mysql 排它鎖無效

閑來無事,用slim做一個小東西(每次訪問會向數(shù)據(jù)庫插入一條記錄),然后用ab測試,壓力測試100次,但是查看數(shù)據(jù)庫只有88條記錄(應該是100條?。?/p>

ab -n 100 -c 100 "http://192.168.100.162/url?url=http://www.baidu.com"

上代碼

    public function encode(string $url): string
    {
        $this->db->pdo->beginTransaction();

        $nextId = $this->getNextId();// 從數(shù)據(jù)庫獲取最大ID
        $shortUrl = $this->from10_to62($nextId);
        $result = $this->saveRecord($nextId, $url, $shortUrl);

        if (empty($result)) {
            $this->db->pdo->rollBack();
            return false;
        }
        file_put_contents('/var/tmp/log.txt', $nextId . PHP_EOL, FILE_APPEND);
        $this->db->pdo->commit();

        return true;
    }

    // 獲取最大值,加了悲觀鎖
    private function getLastId():int
    {
        $result = $this->db->query('select max(id) as last_id from record for update')->fetchAll();
        return !empty($result) ? (int)$result[0]['last_id'] : 1;
    }

看日志

clipboard.png

但是還是沒有100條記錄,
各路神仙,我這是哪里出了問題啊?

回答
編輯回答
心癌

innodb的鎖是需要begin一個事務的(因為默認autocommit是true)
你為什么不直接把id設成自增?
另外你要加鎖的話,innodb是行鎖,需要你寫where的,你這里變成鎖整個表了。

2018年8月9日 22:33