我在我的 PHP 应用程序中使用 cURL 连接到 RESTful API。但是,我最近才发现我没有并行化我的 cURL 连接,因此执行几个连续的连接会导致最终用户出现极端延迟。
我以前没有使用curl_multi
过,在阅读文档后我有点不知所措。如何最好地重构以下代码以利用curl_multi
的并行化?
编辑:我忘了提到我开源了这里使用的 API。这些是我自己的Directed Edge PHP 绑定。因此,如果您愿意,也可以将您的帮助合并到 GitHub 上的代码中,您将被列为贡献者。
这是我在客户端代码中所做的示例:
// Get 100 goal recommendations from Directed Edge
$de = new DirectedEdgeRest();
$item = "user".$uid;
$limit = 100;
$tags = "goal";
$recommendedGoals = $de->getRecommended($item, $tags, $limit);
// Get 100 interest recommendations from Directed Edge
$de = new DirectedEdgeRest();
$item = "user".$uid;
$limit = 100;
$tags = "interest";
$recommendedInterests = $de->getRecommended($item, $tags, $limit);
以下是相关功能DirectedEdgeRest()
/**
* Returns array of recommended result IDs for an item
* @param string $item Item, e.g. "Miles%20Davis"
* @param string $tags Tags as comma delimited string, e.g. "product,page"
* @param int $limit Limit for max results
*
* @return array Recommended result IDs
*/
public function getRecommended($item, $tags, $limit)
{
// Connect to Directed Edge and parse the returned XML
$targeturl = self::buildURL($item, 'recommended', $tags, $limit, 'true');
$response = self::getCurlResponse($targeturl);
$xml = self::parseXML($response);
// Iterate through the XML and place IDs into an array
foreach($xml->item->recommended as $recommended) {
$recommendedResults[] = filter_var($recommended, FILTER_SANITIZE_NUMBER_INT);
}
return $recommendedResults;
}
/**
* Builds URL for cURL
* @param string $item Item, e.g. "Miles%20Davis"
* @param string $type Type of API request: either "related" or "recommended"
* @param string $tags Tags as comma delimited string, e.g. "product,page"
* @param int $limit Limit for max results
* @param string $exclude "true" if you want to exclude linked, "false" otherwise
*
* @return string The target URL
*/
private function buildURL($item, $type, $tags, $limit, $exclude)
{
$targeturl = DE_BASE_URL;
$targeturl .= $item; // Item
$targeturl .= "/" . $type; // Type
$targeturl .= "?tags=" . $tags; // Tags
$targeturl .= "&maxresults=" . $limit; // Limit
$targeturl .= "&excludeLinked=" . $exclude; // Exclude
return $targeturl;
}
/**
* Returns the cURL response given a target URL
* @param string $targeturl The target URL for cURL
*
* @return string cURL Response
*/
private function getCurlResponse($targeturl)
{
$ch = curl_init($targeturl);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}