/**
* swoole 數據庫連接池 BY 凌晨
* 'worker_num' => 20, //worker進程數量
* 'task_worker_num' => 10, //task進程數量 即為維持的MySQL連接的數量
* 'daemonize'=> 1, //設置守護進程
* 'max_request' => 10000, //最大請求數,超過了進程重啟
* 'log_file' => '/www/web/we7/public_html/addons/cibn_leshi/swolle/swoole.log',
* 'dispatch_mode' => 2,/
*/
class server_db_pool {
protected $task_worker_num;
protected $work_num;
protected $max_request;
protected $dispatch_mode;
protected $daemonize;
protected $server_port;
protected $log_file;
protected $db_host;
protected $db_user;
protected $db_pwd;
protected $db_name;
protected $db_port;
public function __construct()
{
$this->server_port = 9508; // server監聽的端口
$this->worker_num = 20;
$this->task_worker_num = 10;
$this->dispatch_mode = 2;
$this->daemonize = 1;
$this->max_request = 10000;
$this->log_file = "/data/www/swoole";
$this->db_host = "127.0.0.1";
$this->db_user = "root";
$this->db_pwd = "rootdrr@qrr3";
$this->db_name = "zkkkkkkk";
$this->db_port = 3306;
$this->serv = new swoole_server("127.0.0.1", $this->server_port);
$this->serv->set( array(
'worker_num'=>$this->worker_num,
'task_worker_num' => $this->task_worker_num,
'max_request' => $this->max_request,
'daemonize' => $this->daemonize,
'log_file' => $this->log_file,
'dispatch_mode' => $this->dispatch_mode,
));
}
public function run(){
$this->serv->on('Receive', array($this, 'onReceive'));
// Task 回調的2個必須函數
$this->serv->on('Task', array($this, 'onTask'));
$this->serv->on('Finish', array($this, 'onFinish'));
$this->serv->start();
}
public function onReceive($serv, $fd, $from_id, $data){
$result = $this->serv->taskwait($data);
if ($result !== false) {
$result=json_decode($result,true);
if ($result['status'] == 'OK') {
$this->serv->send($fd, json_encode($result['data']) . "\n");
} else {
$this->serv->send($fd, $result);
}
return;
} else {
$this->serv->send($fd, "Error. Task timeout\n");
}
}
public function onTask($serv, $task_id, $from_id, $sql){
static $link = null;
HELL:
if ($link == null) {
$link = @mysqli_connect("127.0.0.1", "root", "root", "test");
if (!$link) {
$link = null;
$this->serv->finish("ER:" . mysqli_error($link));
return;
}
}
$result = $link->query($sql);
if (!$result) { //如果查詢失敗了
if(in_array(mysqli_errno($link), [2013, 2006])){//錯誤碼為2013,或者2006,則重連數據庫,重新執行sql
$link = null;
goto HELL;
}else{
$this->serv->finish("ER:" . mysqli_error($link));
return;
}
}
if(preg_match("/^select/i", $sql)){//如果是select操作,就返回關聯數組
$data = array();
while ($fetchResult = mysqli_fetch_assoc($result) ){
$data['data'][]=$fetchResult;
}
}else{//否則直接返回結果
$data['data'] = $result;
}
$data['status']="OK";
$this->serv->finish(json_encode($data));
}
public function onFinish($serv, $task_id, $data){
echo "任務完成";//taskwait 不觸發這個函數。。
}
}
$serv=new server_db_pool();
$serv->run();