服務(wù)端代碼
<?php
$serv = new swoole_server("127.0.0.1", 9501);//監(jiān)聽127.0.0.1
$serv->set(array(
'worker_num' => 100,//這里設(shè)置為CPU的1-4倍最合理
'task_worker_num' => 10, //MySQL連接的數(shù)量
));
function my_onReceive($serv, $fd, $from_id, $data)
{
//taskwait就是投遞一條任務(wù)猴仑,這里直接傳遞SQL語句了
//然后阻塞等待SQL完成
$result = $serv->taskwait($data);
if ($result !== false) {
// list($status, $db_res) = explode(':', $result, 2);
// if ($status == 'OK') {
//數(shù)據(jù)庫操作成功了剥扣,執(zhí)行業(yè)務(wù)邏輯代碼希痴,這里就自動釋放掉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);
//連接到服務(wù)器
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
die("connect failed.");
}
//向服務(wù)器發(fā)送數(shù)據(jù)
if (!$client->send("sql語句"))
{
die("send failed.");
}
//從服務(wù)器接收數(shù)據(jù)
$data = $client->recv();
if (!$data)
{
die("recv failed.");
}
echo '<pre>';
var_dump(json_decode($data)) ;
//關(guān)閉連接
$client->close();