MySQL Deadlock Detection via PHP

前端 未结 2 809
轮回少年
轮回少年 2021-01-07 09:31

What is the best-practice in dealing with MySQL Dead-Locks in PHP? Should I wrap all database calls in a try{}catch{} block and look for the DeadLock error code from the dat

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 09:53

    I'd like to quote these warm words from MySQL's How to Cope with Deadlocks

    Always be prepared to re-issue a transaction if it fails due to deadlock. Deadlocks are not dangerous. Just try again.

    This could be achieved with a pattern like this:

    for ($i = 3; true; $i--) {
        $pdo->beginTransaction();
        try {
    
            // Do the unit of work
    
            $pdo->commit();
            break;
    
        } catch (\PDOException $e) {
            $pdo->rollback();
            if ($i <= 0) {
                throw $e;
            }
        }
    }
    

提交回复
热议问题