代码结构大致是这样的:classserver{private$server;private$conn=null;publicfunction__construct(){if(!$this->initDb())exit("终止启动\n");//连接数据库$this->server=newswoole_websocket_server('111.111.111.111',1234);//实例化server//消息$this->server->on('message',function(swoole_websocket_server$server,$frame){//这里使用数据库连接$conn});//work进程开启$this->server->on('workerStart',function(swoole_websocket_server$server,$worker_id){if($worker_id==0){//每10秒检测一次数据库连接$server->tick(10*1000,function($timer_id){if(!$this->conn->ping()){echo"数据库已断开!正在尝试重新连接...\n";$this->initDb();//连接数据库}});}});$this->server->start();}//连接数据库privatefunctioninitDb(){$conn=newmysqli('127.0.0.1','root','root','test',3306);if($conn->connect_errno){printf("数据库连接失败:%s\n",$conn->connect_error);returnfalse;}else{$conn->set_charset("utf8");echo"连接数据库成功!\n";$this->conn=$conn;returntrue;}}}newserver();每十秒检测mysql连接状态,如果断开连接则重新走initDb,this->$conn重新赋值。然后我手动重启数据库,程序检测到数据库断开之后进行重连,并且连接成功。但是当接收到消息事件使用$conn时,却还是提示mysqlserverhasgoneaway,明明已经重新连接了啊。我猜想,是不是因为swooleserver在注册事件时就绑定了所使用到的变量,所以conn虽然重新赋值了,但是并没有生效到swooleserver里?
相关分类