@sochi-russia

Как перейти с curl на multiCurl?

На сайт ложится слишком большая нагрузка, так как на странице около 20 запросов по АПИ.
Поэтому думаю нужно перейти на многопоточность. Изучал инструкцию, но так и не разобрался.
Суть такова.
При получении ответа от апи создаются файлы с кэшированными данными, откуда потом берется информация для вывода.
Структура запросов вот такая.
Код

1)
<?php
$cache_ttl = 21600; // время жизни кэша в секундах
$cache_file_airlines = "tmp/ish.data";
$cache_file_products = "tmp/ish1.data";
$map = function ($array, $from, $to)
{
$result = [];
if (!empty($array) && is_array($array))
{
foreach ($array as $element)
{
$key = $element[$from] ? : null;
$value = $element[$to] ? : null;
if ($key && $value)
{
$result[$key] = $value;
}
}
}
return $result;
};
if (file_exists($cache_file_airlines) && (time() - filemtime($cache_file_airlines)) < $cache_ttl)
{
// берём кэшированные данные
$get_airlines = file_get_contents($cache_file_airlines);
}
else
{
$get_airlines = file_get_contents('https://site.ru/json/airlines.json');
file_put_contents($cache_file_airlines, $get_airlines);
}
$airlines = array_column($dataAER, 'name','iata');

if (file_exists($cache_file_products) && (time() - filemtime($cache_file_products)) < $cache_ttl)
{
// берём кэшированные данные
$response = file_get_contents($cache_file_products);
}
else
{
$ch = curl_init();
curl_setopt(
  $ch,
  CURLOPT_URL,
  "https://site.ru/v3/prices_for_dates?origin=MOW&destination=AER&token=*******&departure_at=" . date('Y-m-d') );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Access-Token: **********"
));
$response = curl_exec($ch);
curl_close($ch);

file_put_contents($cache_file_products, $response);
}
$products = json_decode($response, true);
$replace_value = function ($key, $val) use ($airlines)
{
$response = $val;
switch ($key)
{
case 'airline':
$response = $airlines[$val];
break;
}
return $response;
} ?>
<div class="table-responsive" style="overflow-x:hidden;background: var(--responsiv-color)!important; display: flex; flex-direction: column; width: 100%;margin-left: auto; margin-right: auto; list-style-type: none;overflow-y:hidden;">
<?php
if (isset($products['data']) && is_array($products['data']))
{
foreach ($products['data'] as $key => $dataAER)
?>


2)
<?php
$cache_ttl = 21600; // время жизни кэша в секундах
$cache_file_airlines = "tmp/ish2.data";
$cache_file_products = "tmp/ish3.data";
$map = function ($array, $from, $to)
{
$result = [];
if (!empty($array) && is_array($array))
{
foreach ($array as $element)
{
$key = $element[$from] ? : null;
$value = $element[$to] ? : null;
if ($key && $value)
{
$result[$key] = $value;
}
}
}
return $result;
};
if (file_exists($cache_file_airlines) && (time() - filemtime($cache_file_airlines)) < $cache_ttl)
{
// берём кэшированные данные
$get_airlines = file_get_contents($cache_file_airlines);
}
else
{
$get_airlines = file_get_contents('https://site.ru/json/airlines.json');
file_put_contents($cache_file_airlines, $get_airlines);
}
$airlines = array_column($dataSIP, 'name','iata');

if (file_exists($cache_file_products) && (time() - filemtime($cache_file_products)) < $cache_ttl)
{
// берём кэшированные данные
$response = file_get_contents($cache_file_products);
}
else
{
$ch = curl_init();
curl_setopt(
  $ch,
  CURLOPT_URL,
  "https://site.ru/v3/prices_for_dates?origin=MOW&destination=SIP&token=******&departure_at=" . date('Y-m-d') );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-Access-Token: ******"
));
$response = curl_exec($ch);
curl_close($ch);

file_put_contents($cache_file_products, $response);
}
$products = json_decode($response, true);
$replace_value = function ($key, $val) use ($airlines)
{
$response = $val;
switch ($key)
{
case 'airline':
$response = $airlines[$val];
break;
}
return $response;
} ?>
 <div class="table-responsive" style="overflow-x:hidden;background: var(--responsiv-color)!important; display: flex; flex-direction: column; width: 100%;margin-left: auto; margin-right: auto; list-style-type: none;overflow-y:hidden;">
<?php
if (isset($products['data']) && is_array($products['data']))
{
foreach ($products['data'] as $key => $dataSIP)
?>


Разница у них в названиях файлов с кэшированными данными и вот этими переменными $dataSIP и $dataAER

Таких запросов на одной странице 21

Как объединить эти запросы в один?
Снизит ли это нагрузку на сервер?
Как по другому можно снизить нагрузку?
  • Вопрос задан
  • 77 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы