【问题标题】:handle multiple request accessing a json file处理访问 json 文件的多个请求
【发布时间】:2019-03-31 03:41:33
【问题描述】:

我有一个带有示例数据的文本中的 json 文件

{"msisdn":"xxxxxxxxxx","productID":"YYYYYYYY","subdate":"2018-09-28 16:30:35","Status":"1"}
{"msisdn":"xxxxxxxxxx","productID":"YYYYYYYY","subdate":"2018-09-28 16:30:35","Status":"1"}

我有一个 php 代码可以检查 json 文件中是否存在现有 msisdn

class JSONObject implements JsonSerializable
{
    public function __construct($json = false)
    {
        if ($json)
            $this->set(json_decode($json, true));
    }
    public function set($data)
    {
        foreach ($data AS $key => $value) {
            if (is_array($value)) {
                $sub = new JSONObject;
                $sub->set($value);
                $value = $sub;
            }
            $this->{$key} = $value;
        }
    }
    public function jsonSerialize()
    {
        return (object) get_object_vars($this);
    }
}

function checkmsisdnallreadyexists($file,$msisdn)
{
    if (is_file($file)) {
         if (($handle = fopen($file, 'r'))) {
            while (!feof($handle)) {
                $line          = trim(fgets($handle));
                 $jsonString    = json_encode(json_decode($line));
                // Here's the sweetness.
                //$class = new JSONObject($jsonString);
                $class         = new JSONObject($jsonString);
                if($class->msisdn == $msisdn)
                {
                    $date1=date_create($class->subdate);
                    $date2=date_create(date('Y-m-d H:i:s'));
                    $diff=date_diff($date1,$date2);
                    if($diff->format('%a') < 31)
                    {
                        fclose($handle);
                        return true;
                    }
                }
            }
            fclose($handle);
         }
    }
    return false;
}

最初一切正常,但是当我的 json 文件有超过 30 000 条记录时,我们会出现读取超时。因为我们在我的服务器上有一个巨大的请求,每小时大约 20 万个请求,从而提高了整个过程的效率。

谁能提供解决方案或替代方法?

注意:这里不能使用数据库

【问题讨论】:

  • 你可以试试file(...) 而不是fopen() ... fclose()。它只读取文件,您可以处理数据而不会阻塞文件超过必要的时间。
  • 感谢您的帮助

标签: php json file nginx


【解决方案1】:

您可以使用file() 代替fopen() and fclose()

function checkmsisdnallreadyexists($msisdn){ 
  $file_array = file('give file path',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
  foreach($file_array as $arr){ 
      $msisdn_array = json_decode($arr,true); 
      $msisdn_value = $msisdn_array['msisdn']; 
      if($msisdn_value == $msisdn) { 
         $date1=date_create($msisdn_array['subdate']); 
         $date2=date_create(date('Y-m-d H:i:s')); 
         $diff=date_diff($date1,$date2); 
         if($diff->format('%a') < 31) { 
             return true; 
         } 
      } 
   } 
}

【讨论】:

  • 感谢您的帮助。这段代码运行速度比我的快(大约 6 倍),但由于交通繁忙,它仍然失败。
猜你喜欢
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2021-11-11
  • 1970-01-01
相关资源
最近更新 更多