php - 如何用Redis解决并发导致数据重复插入MySQL的问题?
淡淡烟草味
淡淡烟草味 2017-05-16 13:01:48
0
4
664

业务场景

有个查询系统,用户查询的时候,如果数据库没有数据,就需要调用第三方查询接口获取数据,然后把数据插入到数据库,再从数据库查出数据返回给用户。【系统基于PHP开发】

问题描述

如果多个用户查询的时候,就会存在多个请求同时去第三方接口查询,就出现了数据重复插入的问题了。

请问这种问题如何解决呢?
是调用第三方接口的时候,用Redis来保证只有一个请求到第三方,从而避免数据的重复查询和插入,还是有其他什么好的方法呢?具体要怎么实现呢?
谢谢!

淡淡烟草味
淡淡烟草味

reply all (4)
伊谢尔伦

Lock mechanism. Before the code enters the operation, check whether the operation is locked. If it is locked, interrupt the operation. Otherwise, proceed to the next operation. The first step is to lock the operation, then execute the code. After executing the code, don't forget to unlock the operation lock. Otherwise, you won’t be able to carry out the execution.

There are many locking codes, and the one given above is one of them. Redismemcachecache files can be used. If the concurrency of operations is relatively high, it is recommended to use redis like the one above. (In fact, it is to use the string data type to assign a value to the lock key {lock}, and when unlocking, the value of the key will be cleared or assigned a value of 0)

$lock_status = $redis->get('lock_state'); if ($lock_status == 0 || empty($lock_status)) { $redis->set('lock_state', 3600, 1); #操作上锁 #操作代码 $redis->set('lock_state', 3600, 0); #操作解锁 } else { #上锁后的操作 }
    为情所困
    //定义锁的时间秒数 $lockSecond = 5; //获取锁定状态 $lockKey="xxx"; $lockStatus = $redis->get($lockKey); if ($lockStatus == 0 || empty($lockStatus)) {//无锁 //1.上锁 $redis->set($lockKey, 1, ['nx', 'ex' => $lockSecond]); //2.业务操作 //3.解锁 $redis->del($lockKey); } else { sleep($lockSecond); //恢复业务操作 }
      小葫芦
      if (true == $redis_handle->set($lock_key, 1, array('nx', 'ex' => 6))) { //插入 }
        迷茫

        The redis "lock" mentioned by the poster is of course feasible
        In addition, can a unique ID be set for the queried data? This is double verification

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!