dongzan9069 2018-04-27 14:49
浏览 982

Laravel队列是否防止并发请求插入重复记录?

We have a Laravel API with a MariaDB database where we are having the issue of duplicate records in the database that are created by concurrent requests.

We assumed that implementing a queue would solve this, by handling one request at a time. But we still have the same issue of duplicate records.

In the application we have a check that looks for duplicates, but of course that won't work for concurrent requests that will create the same record at the same time.

We are unable to use a unique constraint at database level, partially because of Laravel's soft delete mechanism, and partially because of complex business logic that should allow duplicates if the value of one of the fields matches a certain set of values.

We use Redis as the queue driver.

Are we wrong by thinking that the queue should prevent these issues? Or did we somehow made a mistake somewhere implementing the queue?

This is a simplified version of the controller:

class CreateRecordJob extends Job implements SelfHandling
{

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        $data = $this->data;

        // check if we have this record in the database already
        if(!$this->hasDuplicate($data)) {
            $this->createRecord();
        }
    }
}

In config/queue.php we have set Redis as the default queue driver:

'default' => env('QUEUE_DRIVER', 'redis'),

And also in config/queue.php we have this for the redis connection:

'redis' => [
    'driver'     => 'redis',
    'connection' => 'default',
    'queue'      => 'default',
    'expire'     => 60,
],
  • 写回答

1条回答 默认 最新

  • douyan5481 2018-04-27 15:45
    关注

    basicly - not
    you may find implementation of FIFO-compatable queue-drivers laravel has interface Illuminate\Console\Scheduling\Mutex for this purposes, byt yuo need to extend queueManager to use it

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类