我正在尝试使用API发送SMS。它几乎每秒发送一条短信,但我希望使用PHP中的多线程/phreads在一秒钟内发送多条短信。这是怎么可能的,或者我如何至少一次从我的端异步发送多个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);
}
任何想法都将不胜感激。
您不一定需要使用线程异步发送多个HTTP请求。您可以使用非阻塞I/O,multicrl适用于这种情况。有些HTTP客户端支持multicrl。示例(使用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()中创建foreach?当你这样做的时候,就像一个简单的函数,没有多线程。
那么,如何将多线程与pthread结合使用呢
以下是解决您问题的方法:
$thread = array();
foreach ($_POST['data'] as $index => $data) {
$thread[$index] = new MThread($data);
$thread[$index]->start();
}
您应该能够理解此代码的错误。
只需将foreach删除到run()函数中,并使用我的代码,它就可以工作了。
最好将Beanstalk之类的东西与多个工作线程一起使用。