首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用数据库事务重试Laravel脚本10秒

用数据库事务重试Laravel脚本10秒
EN

Stack Overflow用户
提问于 2015-10-07 10:37:14
回答 1查看 1.7K关注 0票数 1

我正在使用Laravel4.2,我有一个巨大的try/catch块来运行数据库事务。有多种类型的例外。

代码语言:javascript
复制
$startTime = 0;
try {

DB::beginTransaction();
//code

DB::commit();

}catch(Exception1 $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process

}catch(Exception2 $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process

}catch(Exception $e){

DB::rollBack();
//so something with this, save in db and throw new Exception
if($startTime < 10) retry the whole process
}

我想让整个过程重试10秒。每次失败时,我都需要回滚更改,然后再试一次。

我怎么才能做好这件事?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-07 10:50:49

我会将整个代码打包成一个执行事务/回滚的函数,并运行该函数,只要它返回false,并且它在不到10 s前就开始运行了。在我脑子里打字,也许我漏掉了什么东西,但我希望你能明白:

代码语言:javascript
复制
function doIt() {
  try {
    DB::beginTransaction();

    /**
     * whatever
     */

    DB::commit();

    return true;
  } catch (Exception $e) {
    DB::rollBack();
    /**
     * do something more if you need
     */

    return false;
  }
}

$start = time();
do {
  $IdidIt = doIt();
} while(!$IdidIt && (time() - $start <= 10));

根据评论,最新消息如下:

代码语言:javascript
复制
function tryFor10Seconds(Closure $closure) {

  $runTheClosure = function ($closure) {
    try {
      DB::beginTransaction();

      $closure();

      DB::commit();

      return true;
    } catch (Exception $e) {
      DB::rollBack();

      // handle the exception if needed, log it or whatever

      return false;
    }
  };

  $start = time();
  do {
    $result = $runTheClosure($closure);
  } while(!$result && (time() - $start <= 10));

  return $result;
}

所以,基本上你会这样说:

代码语言:javascript
复制
$success = tryFor10Seconds(function() use ($model1, $model2, $whatever) {
  $model1->save();
  $model2->save();
  $whatever->doSomethingWithDB();
});

if (!$success) {
  // :(
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32990014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档