Rah*_*eel 2 php multithreading asynchronous pthreads
我正在尝试使用API发送短信.它每秒发送几乎一条SMS但我想在一秒内使用PHP中的多线程/ pthreads发送多条SMS.怎么可能或者我怎样才能至少从我的端到异步发送多个SMS请求到API服务器.
//Threads Class
class MThread extends Thread {
public $data;
public $result;
public function __construct($data){
$this->data = $data;
}
public function run() {
foreach($this->data as $dt_res){
// Send the POST request with cURL
$ch = curl_init("http://www.example.com");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dt_res['to']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->result = $http_code;
/**/
}
}
}
// $_POST['data'] has multi arrays
$request = new MThread($_POST['data']);
if ($request->start()) {
$request->join();
print_r($request->result);
}
Run Code Online (Sandbox Code Playgroud)
任何想法将不胜感激.
小智 6
您不一定需要使用线程异步发送多个HTTP请求.您可以使用非阻塞I/O,在这种情况下,multicurl是合适的.有些HTTP客户端支持多种支持.示例(使用Guzzle 6):
$client = new \GuzzleHttp\Client();
$requestGenerator = function() use ($client) {
$uriList = ['https://www.google.com', 'http://amazon.com', 'http://github.com', 'http://stackoverflow.com'];
foreach ($uriList as $uri) {
$request = new \GuzzleHttp\Psr7\Request('GET', $uri);
$promise = $client->sendAsync($request);
yield $promise;
}
};
$concurrency = 4;
\GuzzleHttp\Promise\each_limit($requestGenerator(), $concurrency, function(\GuzzleHttp\Psr7\Response $response) {
var_dump($response->getBody()->getContents());
}, function(\Exception $e) {
var_dump($e->getMessage());
})->wait();
Run Code Online (Sandbox Code Playgroud)