如果出现多个curl请求同时进行,导致数据库重复插入数据的情况,可以通过文件锁来防止重复插入数据库,实现代码如下:
//文件锁防止进程重复并发
$folder = '/tmp';
$lock = $folder . "/send_count.lock";
$fp = fopen($lock, 'c');
if(!flock($fp, LOCK_EX | LOCK_NB)){
exit('其他进程正在运行中');
}
/*
*
* 所需执行的代码
*
* */
//执行完后关闭文件,防止堵塞
fclose($fp);
测试文件锁的效果可以使用以下代码,进行测试:
//实现并发curl请求函数
function multiRequestUrl($url, $multi_num = 2) {
$curly = array();
$result = array();
$mh = curl_multi_init();
$data = [];
$data = array_pad($data,$multi_num,$url);
foreach ($data as $id => $d) {
$curly[$id] = curl_init();
$url = $d;
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $curly[$id]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
curl_multi_close($mh);
return $result;
}
//指定并发次数
$multi_num = 2;
//并发测试
$re = multiRequestUrl($url,$multi_num);
//打印并发结果
var_dump($re);