php swoole异步处理mysql

php swoole异步处理mysql

//创建websocket服务器对象,监听0.0.0.0:9509端口
//异步测试
$ws = new swoole_websocket_server("0.0.0.0", 9600);

$ws->set(array(
    'worker_num' => 1,
    'max_conn' => 65535,
    /*'daemonize' => true,*/
    'backlog' => 128,
    'task_worker_num' => 1,
));

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {

});

/* $tag 1 初始化玩家信息 */
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {

});



//定时器要写在WorkerStart这个里面哦
$ws->on('WorkerStart', function ($serv, $worker_id) {
    //投递异步任务
    $data=array('wef'=>'wefe');

    $task_id = $serv->task($data);
    echo "Dispath AsyncTask: id=$task_id\n";

    /*执行其他操作*/
    echo'lalalalalalal';
});

/*通用的执行*/
function commonexecute($sql, $zhanwei = '', $isdebug = 0)
{
    try {
        $stmt = \Db::getStmt($sql);
        if (empty($zhanwei)) {
            $isok=$stmt->execute();
        } else {
            $isok=$stmt->execute($zhanwei);
        }
        if ($isdebug) {
            getrepairsql($sql, $zhanwei);
        }
    } catch (\PDOException $e) {
        $errorstr1='mysql语句错误1:'.$e->getMessage().PHP_EOL;
        $errorstr2='mysql语句错误2:'.$sql.PHP_EOL;
        echo $errorstr1;
        echo'</br>';
        echo $errorstr2;
        file_put_contents(__DIR__.'/error.log', date("Y-m-d H:i:s"). " " . $errorstr1.PHP_EOL, FILE_APPEND | LOCK_EX);
        file_put_contents(__DIR__.'/error.log', date("Y-m-d H:i:s"). " " . $errorstr2.PHP_EOL, FILE_APPEND | LOCK_EX);
        exit();
    }
    return $isok;
}
//处理异步任务
$ws->on('task', function ($serv, $task_id, $from_id, $data) {

    echo "New AsyncTask[id=$task_id]".PHP_EOL;
    var_dump($data);
    $sql='select SLEEP(6)';
    $isok=commonexecute($sql);
    //返回任务执行的结果
    $serv->finish("$data -> OK");

});
//处理异步任务的结果
$ws->on('finish', function ($serv, $task_id, $data) {
    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});


//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
});


$ws->start();

可以看出了执行sleep sql语句时候并有堵塞线程

原创文章如转载,请注明本文链接: http://newmiracle.cn/?p=2154

发表评论

电子邮件地址不会被公开。 必填项已用*标注