如何使用PHP防止并发?

时间:2015-02-12 20:48:25

标签: php

我有代码,同时对它进行2次单独调用。它写入数据库。

例如:

$x->KEY = 'ABC'; //Primary key
$x->TIME = date('His') . substr(microtime(), 2, 2); //Primary key
$x->save(); //saves the record in DB 

这两个流程都来自外部服务。所以我无法控制。正如您所看到的,主键涉及TIME,这会导致重复输入错误并且同时发生多次执行。

我已尝试输入数据库条目,描述该进程已执行一次,因此第二个进程不会通过。但是,这导致只有重复数据库错误。

我也尝试用rand($ microsecs)来阻止执行,希望2次调用会选择随机延迟时间,但这并不会一直有效。

您能否建议其他方法来解决此问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试使用以下代码设置TIME键:

$microtime = explode(" ", microtime());
$x->TIME = $microtime[1];
$x->TIME .= str_replace("0.", "", $microtime[0]);


// in a tight for loop there are no duplicates:
// outputs 142377749062793500
//     ... 142377749062799300
//     ... 142377749062804200
//     ... 142377749062809100
//     ... 142377749062813800

//     ... your existing microtime code in the same loop would output:
//     ... 22515348
//     ... 22515348
//     ... 22515348
//     ... 22515348
//     ... 22515348

它比现有的微缩时码更加精确,因此应该更加独特/更少与现有行碰撞的机会。