服务端代码
<?php
$serv = new swoole_server("127.0.0.1", 9501);//监听127.0.0.1
$serv->set(array(
'worker_num' => 100,//这里设置为CPU的1-4倍最合理
'task_worker_num' => 10, //MySQL连接的数量
));
function my_onReceive($serv, $fd, $from_id, $data)
{
//taskwait就是投递一条任务,这里直接传递SQL语句了
//然后阻塞等待SQL完成
$result = $serv->taskwait($data);
if ($result !== false) {
// list($status, $db_res) = explode(':', $result, 2);
// if ($status == 'OK') {
//数据库操作成功了,执行业务逻辑代码,这里就自动释放掉MySQL连接的占用
$serv->send($fd, $result);
// } else {
// $serv->send($fd, $db_res);
// }
return;
} else {
$serv->send($fd, "Error. Task timeout\n");
}
}
function my_onTask($serv, $task_id, $from_id, $sql)
{
static $link = null;
if ($link == null) {
$link = mysqli_connect("host", "username", "password", "dbname");
if (!$link) {
$link = null;
$serv->finish("ER:" . mysqli_error($link));
return;
}
}
$result = $link->query($sql);
if (!$result) {
$serv->finish("ER:" . mysqli_error($link));
return;
}
$data = $result->fetch_all(MYSQLI_ASSOC);
$serv->finish(json_encode($data));
}
function my_onFinish($serv, $data)
{
echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL;
}
$serv->on('Receive', 'my_onReceive');
$serv->on('Task', 'my_onTask');
$serv->on('Finish', 'my_onFinish');
$serv->start();
以下为客户端代码
<?php
$client = new swoole_client(SWOOLE_SOCK_TCP);
//连接到服务器
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
die("connect failed.");
}
//向服务器发送数据
if (!$client->send("sql语句"))
{
die("send failed.");
}
//从服务器接收数据
$data = $client->recv();
if (!$data)
{
die("recv failed.");
}
echo '<pre>';
var_dump(json_decode($data)) ;
//关闭连接
$client->close();