Skip to content

Commit

Permalink
[fix]修复Mysql连接超时问题带来的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Realself-Ma committed Sep 9, 2020
1 parent cf8cfbe commit 8afc078
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 11 deletions.
50 changes: 39 additions & 11 deletions MarioDungeonServer/MysqlServer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,60 @@ int MysqlServer::connect()
LOG_ERROR<<"mysql init falied";
return -1;
}

mysql = mysql_real_connect(mysql,SERVER_IP, "root", "140226", "MarioDungeon", 0, NULL, 0);//连接到数据库
if(real_connect())
{
LOG_ERROR<<"mysql real_connect falied";
return -1;
}

return 0;
}
int MysqlServer::real_connect()
{
mysql = mysql_real_connect(mysql,SERVER_IP, "root", "140226", "MarioDungeon", 0, NULL, 0);//连接到数据库

if(mysql)
{
LOG_INFO<<"MySQL connection success";
int res=mysql_query(mysql, "set names utf8");//设置查询字符集为utf8
if(res!=0)
{
LOG_INFO<<"mysql_query set utf8 error";
return -1;
}
else
LOG_INFO<<"MySQL set utf8 success";
}
else
{
LOG_WARN<<" MySQL connection failed";
return -1;
}
return 0;
return 0;
}
int MysqlServer::sqlQuery(const char *query)
{
int res=mysql_query(mysql, "set names utf8");//设置查询字符集为utf8
if(res!=0)
{
LOG_INFO<<"mysql_query set utf8 error";
return -1;
}
res=mysql_query(mysql,query);
int res=mysql_query(mysql,query);
if(res)
{
return -1;
int flag=mysql_errno(mysql);
if(flag==CR_SERVER_LOST)
{
if(real_connect())
{
LOG_ERROR<<"retry real_connect falied";
return -1;
}
else
{
LOG_INFO<<"retry real_connect success";
res=mysql_query(mysql,query);
if(res)
return -1;
}
}
else
return -1;
}
return 0;
}
Expand Down
2 changes: 2 additions & 0 deletions MarioDungeonServer/MysqlServer.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <sys/types.h>
#include <sys/socket.h>
#include "mysql/mysql.h"
#include "mysql/errmsg.h"
#include "muduo/net/TcpServer.h"
#include "muduo/net/TcpConnection.h"
#include "muduo/base/Logging.h"
Expand All @@ -24,6 +25,7 @@ class MysqlServer
MysqlServer():mysql(nullptr),res_ptr(nullptr),sqlrow(0){}
void brodcast(const string& msg);
int connect();
int real_connect();
int sqlQuery(const char *query);
string Register(char* name,char* password);
string Login(const TcpConnectionPtr& conn,char* name,char* password);
Expand Down
14 changes: 14 additions & 0 deletions MarioDungeonServer/restart.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#! /bin/bash

while true
do
monitor=`ps -ef | grep main | grep -v grep | wc -l `
if [ $monitor -eq 0 ] ;
then
echo "MarioServer program is not running, restart it"
./main 2021
#else
#echo "MarioServer program is running"
fi
sleep 1
done

0 comments on commit 8afc078

Please sign in to comment.