Phpredis: a method to improve the real-time performance of message queuing (recommended)

Time:2019-11-6

The database storage uses the form of list to store two queues. One is used as message queue to save data. The other is used to read data in real time in redis


 $redis->lpush($queenkey, json_encode($array));
    $redis->lpush($listkey, json_encode($array));

/*Message queue instance*/

public function insertinfo()
  {
    $infos = array('info1' => mt_rand(10,100), 'info2' => mt_rand(10,100));
    $this->insertinfos($infos, 'tutorial-list','tutoriallist');
  }



 public function insertinfos($array, $queenkey,$listkey)
  {
    //Connect to the local redis service
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    //Store data in list
    $redis->lpush($queenkey, json_encode($array));
    $redis->lpush($listkey, json_encode($array));

  }

Read logic. When the redis key is gone, read the database and write it back to the list. If there is one, read the redis data

/*Read instance*/

  public function getinfo()
  {
    $sql = 'select * from mobantestinfo';
    $result = $this->getinfos('tutoriallist', $sql);

    //Read redis directly if redis key is not empty
    if(empty($result)){
      //Connect to the local redis service
      $redis = new \Redis();
      $redis->connect('127.0.0.1', 6379);
      //Get the stored data and output
      $result = $redis->lrange('tutoriallist', 0, -1);
      foreach ($result as $k=>$v){
        $result[$k]=json_decode($v,true);
      }
      print_r($result);
      exit();
    }
  }
  
  function getinfos($key, $sql)
  {
    //Connect to the local redis service
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);

    //Get stored data
    $result = $redis->lrange($key, 0, 1);

    if (empty($result)) {
      $VModel = new HuanShanVoteModel();
      $result = $VModel->query($sql);

      //Put the form of cache queue into the database again
       foreach ($result as $k=>$v){
      //This place should be inserted from the right to ensure the same order as the database
        $redis->rpush($key,json_encode($v));
       }
    } else {
      $result=0;

    }


    return $result;
  }

The above is the whole content of phpredis real-time method (recommended) for improving message queuing brought by Xiaobian. I hope you can support developepaer more~

Recommended Today

[Redis5 source code learning] analysis of the randomkey part of redis command

baiyan Command syntax Command meaning: randomly return a key from the currently selected databaseCommand format: RANDOMKEY Command actual combat: 127.0.0.1:6379> keys * 1) “kkk” 2) “key1” 127.0.0.1:6379> randomkey “key1” 127.0.0.1:6379> randomkey “kkk” Return value: random key; nil if database is empty Source code analysis Main process The processing function corresponding to the keys command is […]