Solicitud de curl asíncrono en PHP
asynchronous request (2)
Entonces, lo que desea hacer es la ejecución asincrónica de las solicitudes de cUrl.
Por lo tanto, necesitaría una biblioteca de procesamiento asíncrono / paralelo para php.
pThreads
Una de las bibliotecas de subprocesos prominentes para php es
pthreads
Primero debe obtener el archivo dll / so y guardarlo en el directorio
php/ext
, y habilitar esa extensión en
php.ini
.
Después de eso, este código haría tu trabajo:
class Request1 extends Thread {
$username = ''xxxxx'';
$api_onfleet = ''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'';
$url_onfleet = "https://onfleet.com/api/v2/tasks";
public function run() {
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$request = $this->url.''api/mail.send.json'';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
}
}
class Request2 extends Thread {
$username = ''xxxxx'';
$api_onfleet = ''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'';
$url_onfleet = "https://onfleet.com/api/v2/tasks";
public function run() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_onfleet);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, $this->api_onfleet);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ''{"destination":{"address":{"unparsed":"''.$pickup_address.''"},"notes":"''.$comments.''"},"recipients":[{"name":"''.$name.''","phone":"+61''.$phone.''","notes":"Number of riders: ''.$riders.''"}],"completeBefore":''.$timestamp.'',"pickupTask":"yes","autoAssign":{"mode":"distance"}}'');
$result_pickup = curl_exec($ch);
curl_close($ch);
// Post the Dropoff task to Onfleet
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $this->url_onfleet);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $this->api_onfleet);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, ''{"destination":{"address":{"unparsed":"''.$dropoff_address.''"},"notes":"''.$comments.''"},"recipients":[{"name":"''.$name.''","phone":"+61''.$phone.''","notes":"Number of riders: ''.$riders.''"}],"autoAssign":{"mode":"distance"}}'');
$result_dropoff = curl_exec($curl);
curl_close($curl);
}
}
$req1 = new Request1();
$req1->start();
$req2 = new Request2();
$req2->start();
Entonces, básicamente, necesita crear una clase que extienda la clase
Thread
y todo lo que desee ejecutar de forma asincrónica (más bien de forma paralela), se colocará en la función
run()
de la clase.
Cuando desee iniciar el subproceso, simplemente cree una instancia de la clase en una variable y llame al método de inicio del objeto, como
$threadsObject->start()
y todo en el
run()
se ejecutará en otro subproceso.
Referencia:
Eso es.
CURL asíncrono
La otra forma es usar las funciones asincrónicas cURL integradas .
Entonces, cuando use
curl_multi_*
, su código se vería así:
$username = ''xxxxx'';
$api_onfleet = ''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'';
$url_onfleet = "https://onfleet.com/api/v2/tasks";
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$request = $url.''api/mail.send.json'';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Post the Pickup task to Onfleet
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_onfleet);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, $api_onfleet);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ''{"destination":{"address":{"unparsed":"''.$pickup_address.''"},"notes":"''.$comments.''"},"recipients":[{"name":"''.$name.''","phone":"+61''.$phone.''","notes":"Number of riders: ''.$riders.''"}],"completeBefore":''.$timestamp.'',"pickupTask":"yes","autoAssign":{"mode":"distance"}}'');
$mh = curl_multi_init();
curl_multi_add_handle($mh,$session);
curl_multi_add_handle($mh,$ch);
$active = null;
//execute the handles
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
}
//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
Lectura sugerida:
Estoy ejecutando dos solicitudes de post curl en PHP. Así es como se ven:
//Onfleet API credentials
$username = ''xxxxx'';
$api_onfleet = ''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'';
$url_onfleet = "https://onfleet.com/api/v2/tasks";
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
$request = $url.''api/mail.send.json'';
// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
// Post the Pickup task to Onfleet
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_onfleet);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, $api_onfleet);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ''{"destination":{"address":{"unparsed":"''.$pickup_address.''"},"notes":"''.$comments.''"},"recipients":[{"name":"''.$name.''","phone":"+61''.$phone.''","notes":"Number of riders: ''.$riders.''"}],"completeBefore":''.$timestamp.'',"pickupTask":"yes","autoAssign":{"mode":"distance"}}'');
$result_pickup = curl_exec($ch);
curl_close($ch);
// Post the Dropoff task to Onfleet
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url_onfleet);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $api_onfleet);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, ''{"destination":{"address":{"unparsed":"''.$dropoff_address.''"},"notes":"''.$comments.''"},"recipients":[{"name":"''.$name.''","phone":"+61''.$phone.''","notes":"Number of riders: ''.$riders.''"}],"autoAssign":{"mode":"distance"}}'');
$result_dropoff = curl_exec($curl);
curl_close($curl);
Están funcionando, pero a veces, la segunda solicitud de post curl no se ejecuta.
Me gustaría ejecutar estas dos solicitudes al mismo tiempo.
¿Cómo puedo hacer eso? Tenga en cuenta que toman diferentes opciones en los campos posteriores.
¡Gracias por tu ayuda!