doulong4169 2016-03-03 05:45
浏览 376

在Laravel中结合事务与队列

Is there a way to tell the Queue facade to not automatically persist what was pushed to the queue until I specifically tell it to?

Queue::noPersist()
Queue::push()
Queue::push()
Queue::persist()

See my problem is as follows, my code execution is wrapped in a transaction.

enter image description here

Inside this transaction is some eloquent records being added and right after also a job being pushed to the queue.

queue runs before transaction commits: The issue is that the queue sometimes starts running before my transaction finishes so it tries to reference a record that hasn't yet been "committed".

Provided my design is ok I'm thinking what I really need is for the queue to only submit after the transaction successfully commits: If the transaction fails then the job should also be rolled back so to speak. Or in other words the jobs shouldn't be pushed until after the transaction succeeds.

queue delay I saw laravel has a delay I can add to the queue but I didn't want to hack a random number in there as that's a bit fragile I really just want to only submit the queues if transaction succeeds.

Any guidance or built in features that could be useful to help me out here?

DB::transaction(function() {
    // add record A to DB
    // add JOB to QUEUE (this job starts firing before transaction commits and fails finding the record A)
    // more operations
});
  • 写回答

3条回答 默认 最新

  • douse8732 2016-03-03 06:38
    关注

    Commit happens after your closure function, so if you keep using this structure - you won't be able to enqueue after commit.

    However, Laravel got another way to do transactions (see 'Manually Using Transactions' in Laravel documentation). You could do something like:

    $errors = false;
    
    try {
      DB::beginTransaction();
    
      // All your operations here
    } catch (Exception $e) {
      $errors = true;
      DB::rollBack();
    }
    
    if (!$errors) {
      DB::commit();
    
      // Add to queue
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制