PHP扩展Swoole实现实时异步任务队列示例(2)
客户端
启动服务后,让我们看看如何调用服务。新建测试文件Client_test.php
<?php
class Client
{
private $client;
public function __construct()
{
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect()
{
if (!$this->client->connect("127.0.0.1", 9501, 1)) {
throw new Exception(sprintf('Swoole Error: %s', $this->client->errCode));
}
}
public function send($data)
{
if ($this->client->isConnected()) {
if (!is_string($data)) {
$data = json_encode($data);
}
return $this->client->send($data);
} else {
throw new Exception('Swoole Server does not connected.');
}
}
public function close()
{
$this->client->close();
}
}
$data = array(
"url" => "http://192.168.10.19/send_mail",
"param" => array(
"username" => 'test',
"password" => 'test'
)
);
$client = new Client();
$client->connect();
if ($client->send($data)) {
echo 'success';
} else {
echo 'fail';
}
$client->close();
在上面代码中,url即为任务所在地址,param为所需传递参数。
保存好代码,在命令行或者浏览器中执行Client_test.php,便实现了异步任务队列。你所填写的URL,将会在每次异步任务被提交后,以HTTP GET的方式异步执行。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP扩展开发教程》、《PHP网络编程技巧总结》、《php curl用法总结》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《php字符串(string)用法总结》
希望本文所述对大家PHP程序设计有所帮助。
