我们可以使用这样的PDO事务来确保外部API调用只运行一次吗?

时间:2016-12-02 00:24:06

标签: php mysql pdo transactions

我需要确保外部API调用(可能需要200-300毫秒才能响应)不会运行多次(请参阅我的编辑以更好地解释我正在尝试做什么)。

这是我最终想到的:

// Row isn't updated?
if ($stmt->rowCount() < 1){
    // STOP, It might be running in another code execution (Which is what we're trying to prevent here)
    throw new PDOException('Not updated!');
}

但我有3个问题我不知道答案:

  1. 这是一个好方法吗?或者它可能造成更多弊大于利?

  2. 如果PHP超时并且我们不回滚会发生什么?如果我们不提交,它会自动回滚吗?

  3. 在以下部分代码中:

    https://example.com/?execute_id=15
    

    如果rowCount为0,它将不会回滚任何东西吗? (我不希望它为另一个代码执行回滚相同的查询)

  4. 最后,如果我的案例中有更好的方法或方法来防止双重执行,请告诉我。

    编辑:

    我在这里尝试做的是阻止人们同时从2个不同的浏览器运行此页面(或刷新太快)并在此页面内执行多次外部api调用。

    if ($stmt->rowCount() < 1){...}

    因此,如果它进入DECLARE @Table AS TABLE (Child INT, Parent INT) INSERT INTO @Table VALUES (1,3),(2,1),(7,5) ;WITH cteRecursive AS ( SELECT OriginalChild = Child ,Child ,Parent ,Level = 0 FROM @Table WHERE Child = 2 UNION ALL SELECT c.OriginalChild ,t.Child ,t.Parent ,Level + 1 FROM cteRecursive c INNER JOIN @Table t ON c.Parent = t.Child ) SELECT TOP 1 TopAncestor = Parent FROM cteRecursive ORDER BY Level DESC ,则意味着该行已被另一次执行更新,并且通过抛出execption,它将再次停止调用以下API调用。

    我不知道如何更好地解释它:(

0 个答案:

没有答案