【问题标题】:PHP method execution only from one client at a time一次仅从一个客户端执行 PHP 方法
【发布时间】:2014-04-28 08:49:30
【问题描述】:

我编写了一个类,它从 xml 文件同步数据库并通过电子邮件报告任何警报。

xml 包含产品价格和库存。

仅当 xml 文件时间比上次同步的文件时间更新时才会执行该方法。

这是第一个问题。我怀疑服务器(随机)出于某种原因更改了文件时间,因为虽然没有生成新的 xml 文件,但同步方法仍在运行。

xml文件从本地服务器导出,通过ftp客户端上传到远程服务器 (同步返回)

第二个问题是,在交通繁忙的时间,do_sync 方法会运行不止一次,因为我在电子邮件中不止一次收到警报。

我明白为什么它会被多次调用,所以我创建了一个标志syncing_now,以防止执行。

错误是标志存储在数据库中,由于第一次调用必须更新数据库,所有其他调用都可以运行该方法。

<?php class Sync extends Model{
  public function __construct(){

    parent::__construct();
       $this->syncing_now = $this->db->get($syncing_now);
 }//END constructor

 public function index(){
    if($this->determine_sync()){
    $this->do_sync();
}else{
    return FALSE;
}
 }


 public function determine_sync(){
  if( filemtime($file) <= $this->db->last_sync() or !$this->$syncing_now){
    return FALSE;
  }else{
    return TRUE;
  }
}



public function do_sync(){
   $this->db->update('syncing_now', TRUE);
    //the sync code works fine..
   $this->db->update('syncing_now', FALSE);
}




}

那么我该怎么做才能只运行一次该方法以及如何追踪文件时间更改发生的原因?

感谢所有帮助。

【问题讨论】:

标签: php mysql xml apache


【解决方案1】:

我建议您使用存储同步的表。

id | md5_of_xml_file | synched_date

现在使用LOCK_TABLES 以确保一次只有一个进程可以处理您的同步文件。

锁定同步表。如果锁定失败,请退出。

if (!mysqli_query('LOCK TABLES synchronisations  WRITE')) {
  die();//quit;
}

如果带有 XML 同步文件哈希的条目已经存在,则退出。

$md5Hash = md5_file('yourXmlSyncFile.xml');
$result = null;
$stmt= $mysqli->prepare("SELECT md5_of_xml_file FROM synchronisations 
  WHERE md5_of_xml_file=?");
$stmt->bind_param("s", $md5Hash);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();

if ($result == $md5Hash) {
  die();//quit;
}

否则,请尝试同步文件。如果可行,请添加一个条目,存储您执行此操作的时间以及用于同步的文件的哈希值。

【讨论】:

  • 感谢您的快速响应... LOCK 表解决了多执行和 md5 文件时间问题... 我会尝试一下,虽然我认为它已经解决了。再次感谢。最后一个问题:如果xml文件很大,md5会影响性能吗?
  • 它对我来说适用于大文件,对其他人也适用。 md5_file 相当快。但是,您可以在这个 SO 问题中阅读它:stackoverflow.com/a/3279798/532495
  • @hgtaz 考虑接受我的回答,这样这个问题就不会得到更多不必要的关注。
猜你喜欢
  • 2015-10-18
  • 2018-05-07
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-29
  • 1970-01-01
相关资源
最近更新 更多