diff --git a/AxibugEmuOnline.Server/Common/SQLPool.cs b/AxibugEmuOnline.Server/Common/SQLPool.cs deleted file mode 100644 index 654834cc..00000000 --- a/AxibugEmuOnline.Server/Common/SQLPool.cs +++ /dev/null @@ -1,202 +0,0 @@ -using MySql.Data.MySqlClient; - -namespace AxibugEmuOnline.Server.Common -{ - public static class SQLPool - { - static Queue _ConQueue = new Queue(); - static Dictionary _OutOfSQLPool = new Dictionary(); - static Dictionary _DicSqlRunFunNum = new Dictionary(); - static Dictionary _DicTimeOutSqlRunFunNum = new Dictionary(); - const int DefaultCount = 1; - const int MaxLimit = 5; - static readonly object _sync = new object(); - static MySqlConnectionStringBuilder connBuilder; - - public static void InitConnMgr() - { - connBuilder = new MySqlConnectionStringBuilder(); - connBuilder.Database = Config.cfg.DBName; - connBuilder.Server = Config.cfg.DBIp; - connBuilder.UserID = Config.cfg.DBUname; - connBuilder.Password = Config.cfg.DBPwd; - connBuilder.Port = Config.cfg.DBPort; - //connBuilder.MinimumPoolSize = 40u; - //connBuilder.MaximumPoolSize = 100u; - connBuilder.Pooling = true; - - - Console.WriteLine("SQLPool连接初始化...."); - for (int i = 0; i < DefaultCount; i++) - { - MySqlConnection _conn = conn(); - _conn.Open(); - _ConQueue.Enqueue(_conn); - } - Console.WriteLine("SQLPool初始化完毕,连接数" + _ConQueue.Count); - } - public static MySqlConnection conn() - { - return new MySqlConnection(connBuilder.ConnectionString); - } - - public static MySqlConnection DequeueSQLConn(string FuncStr) - { - Console.WriteLine($"[DequeueSQLConn]{FuncStr}"); - lock (_sync) - { - if (_DicSqlRunFunNum.ContainsKey(FuncStr)) - { - _DicSqlRunFunNum[FuncStr]++; - } - else - { - _DicSqlRunFunNum[FuncStr] = 1L; - } - MySqlConnection _conn = null; - if (_ConQueue.Count < 1) - { - Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + _ConQueue.Count); - _conn = conn(); - _conn.Open(); - } - else - { - MySqlConnection temp = null; - while (_ConQueue.Count > 0) - { - Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + _ConQueue.Count); - temp = _ConQueue.Dequeue(); - if (temp.State == System.Data.ConnectionState.Closed) - { - Console.WriteLine("[DequeueSQLConn]已经断开SQLCount.Count>" + _ConQueue.Count); - temp.Dispose(); - temp = null; - continue; - } - } - - if (temp != null) - { - _conn = temp; - } - else - { - Console.WriteLine("[DequeueSQLConn]连接池全部已断开,重新创建连接"); - _conn = conn(); - _conn.Open(); - } - } - - _OutOfSQLPool.Add(_conn, new Haoyue_PoolTime - { - time = time(), - FuncStr = FuncStr - }); - - return _conn; - } - } - public static void EnqueueSQLConn(MySqlConnection BackConn) - { - lock (_sync) - { - if (_OutOfSQLPool.ContainsKey(BackConn)) - { - _OutOfSQLPool.Remove(BackConn); - } - else - { - Console.WriteLine("出队遗漏的数据出现了!"); - } - if (_ConQueue.Count > MaxLimit) - { - Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count); - BackConn.Close(); - BackConn.Dispose(); - BackConn = null; - } - else - { - _ConQueue.Enqueue(BackConn); - Console.WriteLine("回收SQLPool.Count>" + _ConQueue.Count); - } - } - } - - public static void CheckPoolTimeOut() - { - lock (_sync) - { - long now = time(); - List removeTemp = new List(); - foreach (KeyValuePair o2 in _OutOfSQLPool) - { - if (now - o2.Value.time >= 120) - { - if (_DicTimeOutSqlRunFunNum.ContainsKey(o2.Value.FuncStr)) - { - _DicTimeOutSqlRunFunNum[o2.Value.FuncStr]++; - } - else - { - _DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L; - } - if (_ConQueue.Count > MaxLimit) - { - Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count); - o2.Key.Close(); - } - else - { - Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + _ConQueue.Count); - _ConQueue.Enqueue(o2.Key); - } - removeTemp.Add(o2.Key); - } - } - if (removeTemp.Count() <= 0) - { - return; - } - foreach (MySqlConnection o in removeTemp) - { - if (_OutOfSQLPool.ContainsKey(o)) - { - _OutOfSQLPool.Remove(o); - Console.WriteLine("[超时回收]_OutOfSQLPool清理"); - } - else - { - Console.WriteLine("[超时回收]_OutOfSQLPool清理异常???????"); - } - } - Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + _ConQueue.Count); - } - } - public static long time() - { - return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds); - } - public static void GetPoolState() - { - Console.WriteLine("-----------------查询统计-----------------"); - foreach (KeyValuePair dic2 in _DicSqlRunFunNum) - { - Console.WriteLine(dic2.Key + ":" + dic2.Value); - } - Console.WriteLine("-----------------超时统计-----------------"); - foreach (KeyValuePair dic in _DicTimeOutSqlRunFunNum) - { - Console.WriteLine(dic.Key + ":" + dic.Value); - } - Console.WriteLine("------------------------------------------"); - } - } - - public class Haoyue_PoolTime - { - public long time { get; set; } - public string FuncStr { get; set; } - } -} diff --git a/AxibugEmuOnline.Server/Common/SQLRUN.cs b/AxibugEmuOnline.Server/Common/SQLRUN.cs new file mode 100644 index 00000000..b21e78a1 --- /dev/null +++ b/AxibugEmuOnline.Server/Common/SQLRUN.cs @@ -0,0 +1,72 @@ +using MySql.Data.MySqlClient; + +namespace AxibugEmuOnline.Server.Common +{ + public static class SQLRUN + { + // 移除自定义队列和状态跟踪字典 + private static Dictionary _DicSqlRunFunNum = new Dictionary(); + private static Dictionary _DicTimeOutSqlRunFunNum = new Dictionary(); + + const int DefaultCount = 1; + const int MaxLimit = 10; + static readonly object _sync = new object(); + static MySqlConnectionStringBuilder connBuilder; + + public static void InitConnMgr() + { + // 配置 MySQL 内置连接池 + connBuilder = new MySqlConnectionStringBuilder + { + Database = Config.cfg.DBName, + Server = Config.cfg.DBIp, + UserID = Config.cfg.DBUname, + Password = Config.cfg.DBPwd, + Port = Config.cfg.DBPort, + Pooling = true, // 启用内置连接池 + MinimumPoolSize = DefaultCount, // 最小连接数 + MaximumPoolSize = MaxLimit, // 最大连接数 + }; + + // 初始化时不手动创建连接,依赖连接池自动管理 + Console.WriteLine("SQLPool初始化完成,连接池参数已配置"); + } + + public static MySqlConnection GetConn(string FuncStr) + { + lock (_sync) + { + IncrementFuncCall(FuncStr); + // 直接使用 MySQL 内置连接池获取连接 + var conn = new MySqlConnection(connBuilder.ConnectionString); + conn.Open(); + return conn; + } + } + + public static void GetPoolState() + { + Console.WriteLine("-----------------查询统计-----------------"); + foreach (var entry in _DicSqlRunFunNum) + { + Console.WriteLine($"函数 {entry.Key} 调用次数: {entry.Value}"); + } + Console.WriteLine("-----------------超时统计-----------------"); + foreach (var entry in _DicTimeOutSqlRunFunNum) + { + Console.WriteLine($"函数 {entry.Key} 超时次数: {entry.Value}"); + } + Console.WriteLine("------------------------------------------"); + } + + #region 私有方法(辅助统计逻辑) + private static void IncrementFuncCall(string funcStr) + { + _DicSqlRunFunNum[funcStr] = _DicSqlRunFunNum.ContainsKey(funcStr) ? _DicSqlRunFunNum[funcStr] + 1 : 1; + } + + #endregion + + } + +} \ No newline at end of file diff --git a/AxibugEmuOnline.Server/Manager/AppSrv.cs b/AxibugEmuOnline.Server/Manager/AppSrv.cs index 7a7bf5be..9cfb83ab 100644 --- a/AxibugEmuOnline.Server/Manager/AppSrv.cs +++ b/AxibugEmuOnline.Server/Manager/AppSrv.cs @@ -24,7 +24,7 @@ namespace AxibugEmuOnline.Server g_Log = new LogManager(); Config.LoadConfig(); AESHelper.LoadKeyIVCfg(Config.cfg.AesKey, Config.cfg.AesIv); - SQLPool.InitConnMgr(); + SQLRUN.InitConnMgr(); g_Tick = new TickManager(); g_ClientMgr = new ClientManager(); g_ClientMgr.Init(45000, 120); diff --git a/AxibugEmuOnline.Server/Manager/GameShareManager.cs b/AxibugEmuOnline.Server/Manager/GameShareManager.cs index 1a699060..29d455ad 100644 --- a/AxibugEmuOnline.Server/Manager/GameShareManager.cs +++ b/AxibugEmuOnline.Server/Manager/GameShareManager.cs @@ -21,82 +21,83 @@ namespace AxibugEmuOnline.Server.Manager ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(_socket); Protobuf_Game_Mark_RESP respData = new Protobuf_Game_Mark_RESP(); - MySqlConnection conn = SQLPool.DequeueSQLConn("RecvGameMark"); - try + using (MySqlConnection conn = SQLRUN.GetConn("RecvGameMark")) { - string query = "SELECT id from rom_stars where uid = ?uid and romid = ?romid"; - bool bHad = false; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?romid", msg.RomID); - using (var reader = command.ExecuteReader()) + string query = "SELECT id from rom_stars where uid = ?uid and romid = ?romid"; + bool bHad = false; + using (var command = new MySqlCommand(query, conn)) { - while (reader.Read()) + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?romid", msg.RomID); + using (var reader = command.ExecuteReader()) { - bHad = true; - break; + while (reader.Read()) + { + bHad = true; + break; + } } } - } - //收藏 - if (msg.Motion == 1) - { - if (bHad) + //收藏 + if (msg.Motion == 1) { - AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorRomAlreadyHadStar, ProtoBufHelper.Serizlize(respData)); - return; - } - else - { - query = "INSERT INTO `haoyue_emu`.`rom_stars` (`uid`, `romid`) VALUES (?uid, ?romid);"; - using (var command = new MySqlCommand(query, conn)) + if (bHad) { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?romid", msg.RomID); - command.ExecuteNonQuery(); + AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorRomAlreadyHadStar, ProtoBufHelper.Serizlize(respData)); + return; + } + else + { + query = "INSERT INTO `haoyue_emu`.`rom_stars` (`uid`, `romid`) VALUES (?uid, ?romid);"; + using (var command = new MySqlCommand(query, conn)) + { + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?romid", msg.RomID); + command.ExecuteNonQuery(); + } } } - } - else//取消收藏 - { - if (bHad) + else//取消收藏 { - query = "DELETE from rom_stars where uid = ?uid and romid = ?romid"; - using (var command = new MySqlCommand(query, conn)) + if (bHad) { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?romid", msg.RomID); - command.ExecuteNonQuery(); + query = "DELETE from rom_stars where uid = ?uid and romid = ?romid"; + using (var command = new MySqlCommand(query, conn)) + { + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?romid", msg.RomID); + command.ExecuteNonQuery(); + } + } + else + { + AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorRomDontHadStar, ProtoBufHelper.Serizlize(respData)); + return; } } - else + //更新收藏数 + query = "update romlist set stars = (SELECT COUNT(id) from rom_stars where rom_stars.romid = ?romid) where romlist.id = ?romid"; + using (var command = new MySqlCommand(query, conn)) { - AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorRomDontHadStar, ProtoBufHelper.Serizlize(respData)); - return; + command.Parameters.AddWithValue("?romid", msg.RomID); + command.ExecuteNonQuery(); } - } - //更新收藏数 - query = "update romlist set stars = (SELECT COUNT(id) from rom_stars where rom_stars.romid = ?romid) where romlist.id = ?romid"; - using (var command = new MySqlCommand(query, conn)) - { - command.Parameters.AddWithValue("?romid", msg.RomID); - command.ExecuteNonQuery(); - } - } - catch (Exception e) - { + } + catch (Exception e) + { + } } respData.Stars = GetRomStart(msg.RomID); respData.IsStar = CheckIsRomStar(msg.RomID, _c.UID) ? 1 : 0; - SQLPool.EnqueueSQLConn(conn); respData.RomID = msg.RomID; AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGameMark, (int)ErrorCode.ErrorOk, ProtoBufHelper.Serizlize(respData)); } @@ -104,59 +105,61 @@ namespace AxibugEmuOnline.Server.Manager public int GetRomStart(int RomId) { int stars = 0; - MySqlConnection conn = SQLPool.DequeueSQLConn("GetStart"); - try + using (MySqlConnection conn = SQLRUN.GetConn("GetStart")) { - string query = $"SELECT `stars` FROM romlist where id = ?romid;"; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?RomID", RomId); - // 执行查询并处理结果 - using (var reader = command.ExecuteReader()) + string query = $"SELECT `stars` FROM romlist where id = ?romid;"; + using (var command = new MySqlCommand(query, conn)) { - while (reader.Read()) + // 设置参数值 + command.Parameters.AddWithValue("?RomID", RomId); + // 执行查询并处理结果 + using (var reader = command.ExecuteReader()) { - stars = reader.GetInt32(0); + while (reader.Read()) + { + stars = reader.GetInt32(0); + } } } } + catch (Exception e) + { + AppSrv.g_Log.Error(e); + } } - catch (Exception e) - { - AppSrv.g_Log.Error(e); - } - SQLPool.EnqueueSQLConn(conn); return stars; } public bool CheckIsRomStar(int RomId, long uid) { bool bhad = false; - MySqlConnection conn = SQLPool.DequeueSQLConn("CheckIsRomStart"); - try + using (MySqlConnection conn = SQLRUN.GetConn("CheckIsRomStart")) { - string query = $"SELECT count(id) from rom_stars where uid = ?uid and romid = ?romid"; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?romid", RomId); - command.Parameters.AddWithValue("?uid", uid); - // 执行查询并处理结果 - using (var reader = command.ExecuteReader()) + string query = $"SELECT count(id) from rom_stars where uid = ?uid and romid = ?romid"; + using (var command = new MySqlCommand(query, conn)) { - while (reader.Read()) + // 设置参数值 + command.Parameters.AddWithValue("?romid", RomId); + command.Parameters.AddWithValue("?uid", uid); + // 执行查询并处理结果 + using (var reader = command.ExecuteReader()) { - bhad = reader.GetInt32(0) > 0; + while (reader.Read()) + { + bhad = reader.GetInt32(0) > 0; + } } } } + catch (Exception e) + { + AppSrv.g_Log.Error("CheckIsRomStar:" + e); + } } - catch (Exception e) - { - AppSrv.g_Log.Error("CheckIsRomStar:"+e); - } - SQLPool.EnqueueSQLConn(conn); return bhad; } @@ -166,7 +169,8 @@ namespace AxibugEmuOnline.Server.Manager return ptype; ptype = RomPlatformType.Invalid; - MySqlConnection conn = SQLPool.DequeueSQLConn("GetRomPlatformType"); + using (MySqlConnection conn = SQLRUN.GetConn("GetRomPlatformType")) + { try { string query = "SELECT PlatformType from romlist where Id = ?RomID "; @@ -188,12 +192,11 @@ namespace AxibugEmuOnline.Server.Manager { AppSrv.g_Log.Error(e); } + } if (ptype == RomPlatformType.Invalid) AppSrv.g_Log.Error($"RomID {RomID} 没找到平台配置"); - SQLPool.EnqueueSQLConn(conn); - return ptype; } } diff --git a/AxibugEmuOnline.Server/Manager/LoginManager.cs b/AxibugEmuOnline.Server/Manager/LoginManager.cs index c9c26e82..63f5a2ed 100644 --- a/AxibugEmuOnline.Server/Manager/LoginManager.cs +++ b/AxibugEmuOnline.Server/Manager/LoginManager.cs @@ -79,25 +79,26 @@ namespace AxibugEmuOnline.Server.Manager bool bDone = false; ClientInfo _c = AppSrv.g_ClientMgr.GetClientForSocket(socket); Protobuf_Modify_NickName msg = ProtoBufHelper.DeSerizlize(reqData); - MySqlConnection conn = SQLPool.DequeueSQLConn("ModifyNikeName"); - try + using (MySqlConnection conn = SQLRUN.GetConn("ModifyNikeName")) { - string query = "update users set nikename = ?nikename where uid = ?uid "; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?nikename", msg.NickName); - if (command.ExecuteNonQuery() > 0) + string query = "update users set nikename = ?nikename where uid = ?uid "; + using (var command = new MySqlCommand(query, conn)) { - bDone = true; + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?nikename", msg.NickName); + if (command.ExecuteNonQuery() > 0) + { + bDone = true; + } } } + catch (Exception e) + { + } } - catch (Exception e) - { - } - SQLPool.EnqueueSQLConn(conn); if (bDone) { @@ -132,34 +133,15 @@ namespace AxibugEmuOnline.Server.Manager { uid = 0; bool bDone = true; - MySqlConnection conn = SQLPool.DequeueSQLConn("GetUidByDevice"); - try + using (MySqlConnection conn = SQLRUN.GetConn("GetUidByDevice")) { - string query = "SELECT uid from user_devices where device = ?deviceStr "; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?deviceStr", deviceStr); - // 执行查询并处理结果 - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - uid = reader.GetInt64(0); - } - } - } - - if (uid > 0) - { - AppSrv.g_Log.Info($"设备串:{deviceStr} 对应 UID:{uid}"); - } - else - { - query = "INSERT INTO `haoyue_emu`.`users` (`nikename`, `regdate`,`lastlogindate`) VALUES (NULL,now(),now());SELECT LAST_INSERT_ID(); "; + string query = "SELECT uid from user_devices where device = ?deviceStr "; using (var command = new MySqlCommand(query, conn)) { // 设置参数值 + command.Parameters.AddWithValue("?deviceStr", deviceStr); // 执行查询并处理结果 using (var reader = command.ExecuteReader()) { @@ -170,39 +152,59 @@ namespace AxibugEmuOnline.Server.Manager } } - //设置默认名字 - query = "update users set nikename = ?nikename where uid = ?uid "; - using (var command = new MySqlCommand(query, conn)) + if (uid > 0) { - // 设置参数值 - command.Parameters.AddWithValue("?uid", uid); - command.Parameters.AddWithValue("?nikename", GetRandomNickName(uid)); - if (command.ExecuteNonQuery() < 1) + AppSrv.g_Log.Info($"设备串:{deviceStr} 对应 UID:{uid}"); + } + else + { + query = "INSERT INTO `haoyue_emu`.`users` (`nikename`, `regdate`,`lastlogindate`) VALUES (NULL,now(),now());SELECT LAST_INSERT_ID(); "; + using (var command = new MySqlCommand(query, conn)) { - bDone = false; + // 设置参数值 + // 执行查询并处理结果 + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + uid = reader.GetInt64(0); + } + } } + + //设置默认名字 + query = "update users set nikename = ?nikename where uid = ?uid "; + using (var command = new MySqlCommand(query, conn)) + { + // 设置参数值 + command.Parameters.AddWithValue("?uid", uid); + command.Parameters.AddWithValue("?nikename", GetRandomNickName(uid)); + if (command.ExecuteNonQuery() < 1) + { + bDone = false; + } + } + + query = "INSERT INTO `haoyue_emu`.`user_devices` (`device`, `devicetype`, `uid`) VALUES (?deviceStr, ?DeviceType, ?uid);"; + using (var command = new MySqlCommand(query, conn)) + { + command.Parameters.AddWithValue("?deviceStr", deviceStr); + command.Parameters.AddWithValue("?DeviceType", (int)DeviceType); + command.Parameters.AddWithValue("?uid", uid); + if (command.ExecuteNonQuery() < 1) + bDone = false; + } + + AppSrv.g_Log.Info($"创建新账户,设备:{deviceStr},设备类型:{DeviceType.ToString()},是否成功:{bDone}"); } - query = "INSERT INTO `haoyue_emu`.`user_devices` (`device`, `devicetype`, `uid`) VALUES (?deviceStr, ?DeviceType, ?uid);"; - using (var command = new MySqlCommand(query, conn)) - { - command.Parameters.AddWithValue("?deviceStr", deviceStr); - command.Parameters.AddWithValue("?DeviceType", (int)DeviceType); - command.Parameters.AddWithValue("?uid", uid); - if (command.ExecuteNonQuery() < 1) - bDone = false; - } - - AppSrv.g_Log.Info($"创建新账户,设备:{deviceStr},设备类型:{DeviceType.ToString()},是否成功:{bDone}"); } - + catch (Exception e) + { + AppSrv.g_Log.Error($"ex=>{e.ToString()}"); + bDone = false; + } } - catch (Exception e) - { - AppSrv.g_Log.Error($"ex=>{e.ToString()}"); - bDone = false; - } - SQLPool.EnqueueSQLConn(conn); if (uid <= 0) bDone = false; @@ -211,41 +213,42 @@ namespace AxibugEmuOnline.Server.Manager public void UpdateUserData(long uid, ClientInfo _c, DeviceType deviceType) { - MySqlConnection conn = SQLPool.DequeueSQLConn("UpdateUserData"); - try + using (MySqlConnection conn = SQLRUN.GetConn("UpdateUserData")) { - string query = "SELECT account,nikename,regdate,lastlogindate from users where uid = ?uid "; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?uid", uid); - // 执行查询并处理结果 - using (var reader = command.ExecuteReader()) + string query = "SELECT account,nikename,regdate,lastlogindate from users where uid = ?uid "; + using (var command = new MySqlCommand(query, conn)) { - while (reader.Read()) + // 设置参数值 + command.Parameters.AddWithValue("?uid", uid); + // 执行查询并处理结果 + using (var reader = command.ExecuteReader()) { + while (reader.Read()) + { - _c.Account = reader.IsDBNull(0) ? string.Empty : reader.GetString(0); - _c.NickName = reader.IsDBNull(1) ? string.Empty : reader.GetString(1); - _c.LogInDT = DateTime.Now; - _c.RegisterDT = reader.IsDBNull(2) ? DateTime.Now : reader.GetDateTime(2); - _c.LastLogInDT = reader.IsDBNull(3) ? DateTime.Now : reader.GetDateTime(3); - _c.deviceType = deviceType; + _c.Account = reader.IsDBNull(0) ? string.Empty : reader.GetString(0); + _c.NickName = reader.IsDBNull(1) ? string.Empty : reader.GetString(1); + _c.LogInDT = DateTime.Now; + _c.RegisterDT = reader.IsDBNull(2) ? DateTime.Now : reader.GetDateTime(2); + _c.LastLogInDT = reader.IsDBNull(3) ? DateTime.Now : reader.GetDateTime(3); + _c.deviceType = deviceType; + } } } + query = "update users set lastlogindate = now() where uid = ?uid "; + using (var command = new MySqlCommand(query, conn)) + { + command.Parameters.AddWithValue("?uid", uid); + command.ExecuteNonQuery(); + } } - query = "update users set lastlogindate = now() where uid = ?uid "; - using (var command = new MySqlCommand(query, conn)) + catch (Exception e) { - command.Parameters.AddWithValue("?uid", uid); - command.ExecuteNonQuery(); + } } - catch (Exception e) - { - - } - SQLPool.EnqueueSQLConn(conn); } static string GenToken(ClientInfo _c) diff --git a/AxibugEmuOnline.Server/Manager/RoomManager.cs b/AxibugEmuOnline.Server/Manager/RoomManager.cs index 87646756..23c5f5ed 100644 --- a/AxibugEmuOnline.Server/Manager/RoomManager.cs +++ b/AxibugEmuOnline.Server/Manager/RoomManager.cs @@ -109,10 +109,9 @@ namespace AxibugEmuOnline.Server } public void RoomLog(long uid, int platform, int RoomID, int RomID, RoomLogType state) { - MySqlConnection conn = SQLPool.DequeueSQLConn("RoomLog"); - try + string query = "INSERT INTO `haoyue_emu`.`room_log` (`uid`, `platform`, `romid`,`roomid`, `state`) VALUES ( ?uid, ?platform, ?romid, ?roomid, ?state);"; + using (MySqlConnection conn = SQLRUN.GetConn("RoomLog")) { - string query = "INSERT INTO `haoyue_emu`.`room_log` (`uid`, `platform`, `romid`,`roomid`, `state`) VALUES ( ?uid, ?platform, ?romid, ?roomid, ?state);"; using (var command = new MySqlCommand(query, conn)) { // 设置参数值 @@ -134,10 +133,6 @@ namespace AxibugEmuOnline.Server } } } - catch (Exception e) - { - } - SQLPool.EnqueueSQLConn(conn); } #endregion @@ -240,7 +235,7 @@ namespace AxibugEmuOnline.Server Data_RoomData newRoom = new Data_RoomData(); RomPlatformType ptype = AppSrv.g_GameShareMgr.GetRomPlatformType(msg.GameRomID); - newRoom.Init(GetNewRoomID(), msg.GameRomID, msg.GameRomHash, _c.UID, false,ptype); + newRoom.Init(GetNewRoomID(), msg.GameRomID, msg.GameRomHash, _c.UID, false, ptype); AddRoom(newRoom); ErrorCode joinErrcode = ErrorCode.ErrorOk; //加入 @@ -844,7 +839,7 @@ namespace AxibugEmuOnline.Server } break; } - + } /// /// 更新同步名单 @@ -1291,7 +1286,7 @@ namespace AxibugEmuOnline.Server } AppSrv.g_Log.Debug($"Join _c.UID->{_c.UID} RoomID->{RoomID}"); Dictionary slotInfo = new Dictionary(); - slotInfo[slotIdx] = (joyIdx,GamePadType.GlobalGamePad); + slotInfo[slotIdx] = (joyIdx, GamePadType.GlobalGamePad); SetPlayerSlotData(_c, ref slotInfo); int newPlayerCount = GetPlayerCount(); errcode = ErrorCode.ErrorOk; diff --git a/AxibugEmuOnline.Server/Manager/SavDataManager.cs b/AxibugEmuOnline.Server/Manager/SavDataManager.cs index 3c6a5195..60524150 100644 --- a/AxibugEmuOnline.Server/Manager/SavDataManager.cs +++ b/AxibugEmuOnline.Server/Manager/SavDataManager.cs @@ -28,11 +28,11 @@ namespace AxibugEmuOnline.Server.Manager respData.SavDataList.Add(nulldata); respData.SavDataList.Add(nulldata); respData.SavDataList.Add(nulldata); - MySqlConnection conn = SQLPool.DequeueSQLConn("RecvGameMark"); - try + + string query = "SELECT `id`,`uid`,`romid`, `savidx`, `savName`,`savNote`, `savUrl`,`savImgUrl`, `savDate` from user_gamesavedata where uid = ?uid and romid = ?romid"; + bool bHad = false; + using (MySqlConnection conn = SQLRUN.GetConn("RecvGameMark")) { - string query = "SELECT `id`,`uid`,`romid`, `savidx`, `savName`,`savNote`, `savUrl`,`savImgUrl`, `savDate` from user_gamesavedata where uid = ?uid and romid = ?romid"; - bool bHad = false; using (var command = new MySqlCommand(query, conn)) { // 设置参数值 @@ -60,12 +60,7 @@ namespace AxibugEmuOnline.Server.Manager } } } - } - catch (Exception e) - { - } - SQLPool.EnqueueSQLConn(conn); respData.RomID = msg.RomID; AppSrv.g_ClientMgr.ClientSend(_c, (int)CommandID.CmdGamesavGetGameSavList, (int)ErrorCode.ErrorOk, ProtoBufHelper.Serizlize(respData)); @@ -79,10 +74,10 @@ namespace AxibugEmuOnline.Server.Manager ErrorCode errCode = ErrorCode.ErrorOk; respData.RomID = msg.RomID; bool bHad = false; string SavUrl = null; string SavImgUrl = null; - MySqlConnection conn = SQLPool.DequeueSQLConn("RecvGameMark"); - try + + string query = "SELECT `savUrl`,`savImgUrl`, `savDate` from user_gamesavedata where uid = ?uid and romid = ?romid and savidx = ?savidx"; + using (MySqlConnection conn = SQLRUN.GetConn("RecvGameMark")) { - string query = "SELECT `savUrl`,`savImgUrl`, `savDate` from user_gamesavedata where uid = ?uid and romid = ?romid and savidx = ?savidx"; using (var command = new MySqlCommand(query, conn)) { // 设置参数值 @@ -98,44 +93,40 @@ namespace AxibugEmuOnline.Server.Manager } } } - } - catch (Exception e) - { - } - if (!bHad) - { - errCode = ErrorCode.ErrorRomDontHadSavedata; - } - else - { - bool bDelSav = FileDelete(Path.Combine(Config.cfg.savDataPath, SavUrl)); - bool bDelImg = FileDelete(Path.Combine(Config.cfg.savDataPath, SavImgUrl)); - if (!bDelSav || !bDelImg) + if (!bHad) { errCode = ErrorCode.ErrorRomDontHadSavedata; } else { - try + bool bDelSav = FileDelete(Path.Combine(Config.cfg.savDataPath, SavUrl)); + bool bDelImg = FileDelete(Path.Combine(Config.cfg.savDataPath, SavImgUrl)); + if (!bDelSav || !bDelImg) { - string query = "delete from user_gamesavedata where uid = ?uid and romid = ?romid and savidx = ?savidx"; - using (var command = new MySqlCommand(query, conn)) + errCode = ErrorCode.ErrorRomDontHadSavedata; + } + else + { + try { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?romid", msg.RomID); - if (command.ExecuteNonQuery() < 1) + query = "delete from user_gamesavedata where uid = ?uid and romid = ?romid and savidx = ?savidx"; + using (var command = new MySqlCommand(query, conn)) { - AppSrv.g_Log.Error("删除即时存档,但是他并没有."); + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?romid", msg.RomID); + if (command.ExecuteNonQuery() < 1) + { + AppSrv.g_Log.Error("删除即时存档,但是他并没有."); + } } } + catch { } } - catch { } } } - SQLPool.EnqueueSQLConn(conn); if (errCode == ErrorCode.ErrorOk) { @@ -174,7 +165,6 @@ namespace AxibugEmuOnline.Server.Manager if (errCode == ErrorCode.ErrorOk) { - MySqlConnection conn = SQLPool.DequeueSQLConn("RecvUpLoadGameSav"); byte[] StateRawData = msg.StateRaw.ToArray(); byte[] ImgData = msg.SavImg.ToArray(); GetNewRomPath(_c.UID, ptype, msg.RomID, msg.SavDataIdx, $"{msg.SavDataIdx}.axisav", out string rompath); @@ -190,25 +180,27 @@ namespace AxibugEmuOnline.Server.Manager " ( `uid`, `romid`, `savidx`, `savName`, `savNote`, `savUrl`, `savImgUrl`, `savDate`)" + " VALUES ( ?uid, ?romid, ?savidx, ?savName, ?savNote, ?savUrl, ?savImgUrl, ?savDate);"; - using (var command = new MySqlCommand(query, conn)) + + using (MySqlConnection conn = SQLRUN.GetConn("RecvUpLoadGameSav")) { - // 设置参数值 - command.Parameters.AddWithValue("?uid", _c.UID); - command.Parameters.AddWithValue("?romid", msg.RomID); - command.Parameters.AddWithValue("?savidx", msg.SavDataIdx); - command.Parameters.AddWithValue("?savName", msg.Name); - command.Parameters.AddWithValue("?savNote", msg.Note); - command.Parameters.AddWithValue("?savUrl", rompath); - command.Parameters.AddWithValue("?savImgUrl", imgpath); - command.Parameters.AddWithValue("?savDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); - if (command.ExecuteNonQuery() < 1) + using (var command = new MySqlCommand(query, conn)) { - AppSrv.g_Log.Error("执行即时存档保存失败"); + // 设置参数值 + command.Parameters.AddWithValue("?uid", _c.UID); + command.Parameters.AddWithValue("?romid", msg.RomID); + command.Parameters.AddWithValue("?savidx", msg.SavDataIdx); + command.Parameters.AddWithValue("?savName", msg.Name); + command.Parameters.AddWithValue("?savNote", msg.Note); + command.Parameters.AddWithValue("?savUrl", rompath); + command.Parameters.AddWithValue("?savImgUrl", imgpath); + command.Parameters.AddWithValue("?savDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); + if (command.ExecuteNonQuery() < 1) + { + AppSrv.g_Log.Error("执行即时存档保存失败"); + } } } } - - SQLPool.EnqueueSQLConn(conn); } @@ -273,44 +265,45 @@ namespace AxibugEmuOnline.Server.Manager bool bhad = false; protoData = default; RomPlatformType ptype = AppSrv.g_GameShareMgr.GetRomPlatformType(romid); - MySqlConnection conn = SQLPool.DequeueSQLConn("GetProtobufMineGameSavInfo"); - try + using (MySqlConnection conn = SQLRUN.GetConn("GetProtobufMineGameSavInfo")) { - string query = "SELECT `id`,`uid`, `romid`, `savidx`, `savName`, `savNote`, `savUrl`, `savImgUrl`, `savDate` from `user_gamesavedata` where uid = ?uid and romid = ?romid and savidx = ?savidx"; - using (var command = new MySqlCommand(query, conn)) + try { - // 设置参数值 - command.Parameters.AddWithValue("?uid", uid); - command.Parameters.AddWithValue("?romid", romid); - command.Parameters.AddWithValue("?savidx", savIdx); - using (var reader = command.ExecuteReader()) + string query = "SELECT `id`,`uid`, `romid`, `savidx`, `savName`, `savNote`, `savUrl`, `savImgUrl`, `savDate` from `user_gamesavedata` where uid = ?uid and romid = ?romid and savidx = ?savidx"; + using (var command = new MySqlCommand(query, conn)) { - while (reader.Read()) + // 设置参数值 + command.Parameters.AddWithValue("?uid", uid); + command.Parameters.AddWithValue("?romid", romid); + command.Parameters.AddWithValue("?savidx", savIdx); + using (var reader = command.ExecuteReader()) { - protoData = new Protobuf_Mine_GameSavInfo() + while (reader.Read()) { - BHadSaveData = true, - SavID = reader.GetInt64(0), - Uid = reader.GetInt64(1), - RomID = reader.GetInt32(2), - SavDataIdx = reader.GetInt32(3), - SavName = reader.GetString(4), - Note = reader.GetString(5), - SavUrl = reader.GetString(6), - SavImgUrl = reader.GetString(7), - SavDate = reader.GetDateTime(8).ToString("yyyy-MM-dd HH:mm:ss"), - GamePlatformType = ptype - }; - bhad = true; - break; + protoData = new Protobuf_Mine_GameSavInfo() + { + BHadSaveData = true, + SavID = reader.GetInt64(0), + Uid = reader.GetInt64(1), + RomID = reader.GetInt32(2), + SavDataIdx = reader.GetInt32(3), + SavName = reader.GetString(4), + Note = reader.GetString(5), + SavUrl = reader.GetString(6), + SavImgUrl = reader.GetString(7), + SavDate = reader.GetDateTime(8).ToString("yyyy-MM-dd HH:mm:ss"), + GamePlatformType = ptype + }; + bhad = true; + break; + } } } } + catch (Exception e) + { + } } - catch (Exception e) - { - } - SQLPool.EnqueueSQLConn(conn); return bhad; } @@ -318,8 +311,7 @@ namespace AxibugEmuOnline.Server.Manager { bool bDone = false; RomPlatformType ptype = AppSrv.g_GameShareMgr.GetRomPlatformType(romid); - MySqlConnection conn = SQLPool.DequeueSQLConn("DeleteProtobufMineGameSavInfo"); - try + using (MySqlConnection conn = SQLRUN.GetConn("DeleteProtobufMineGameSavInfo")) { string query = "delete from `user_gamesavedata` where uid = ?uid and romid = ?romid and savidx = ?savidx"; using (var command = new MySqlCommand(query, conn)) @@ -331,10 +323,6 @@ namespace AxibugEmuOnline.Server.Manager bDone = command.ExecuteNonQuery() > 0; } } - catch (Exception e) - { - } - SQLPool.EnqueueSQLConn(conn); return bDone; } } diff --git a/AxibugEmuOnline.Server/Program.cs b/AxibugEmuOnline.Server/Program.cs index 63f9beec..70dc50bf 100644 --- a/AxibugEmuOnline.Server/Program.cs +++ b/AxibugEmuOnline.Server/Program.cs @@ -87,6 +87,11 @@ namespace AxibugEmuOnline.Server AppSrv.g_GameShareMgr.RecvGameMark(null, null); } break; + case "sql": + { + SQLRUN.GetPoolState(); + } + break; default: Console.WriteLine("未知命令" + CommandStr); break; @@ -98,58 +103,59 @@ namespace AxibugEmuOnline.Server static void UpdateRomHash() { AppSrv.g_Log.Info("UpdateRomHash"); - MySqlConnection conn = SQLPool.DequeueSQLConn("UpdateRomHash"); - try + using (MySqlConnection conn = SQLRUN.GetConn("UpdateRomHash")) { - List<(int id, string romurl, string name)> list = new List<(int id, string romurl, string name)>(); - List<(int id, string romurl, string name)> Nonelist = new List<(int id, string romurl, string name)>(); - - string query = $"SELECT id,`Name`,GameType,Note,RomUrl,ImgUrl,`Hash` FROM romlist"; - using (var command = new MySqlCommand(query, conn)) + try { - // 执行查询并处理结果 - using (var reader = command.ExecuteReader()) - { - while (reader.Read()) - { - list.Add( - (reader.GetInt32(0), - !reader.IsDBNull(4) ? reader.GetString(4) : string.Empty, - !reader.IsDBNull(1) ? reader.GetString(1) : string.Empty - )); - } - } - } + List<(int id, string romurl, string name)> list = new List<(int id, string romurl, string name)>(); + List<(int id, string romurl, string name)> Nonelist = new List<(int id, string romurl, string name)>(); - for (int i = 0; i < list.Count; i++) - { - string rompath = Config.cfg.RomDir + "/" + list[i].romurl; - rompath = System.Net.WebUtility.UrlDecode(rompath); - if (!File.Exists(rompath)) - { - Nonelist.Add(list[i]); - continue; - } - string romhash = Helper.FileMD5Hash(rompath); - AppSrv.g_Log.Info($"第{i}个,Name->{list[i].name},Hash->{romhash}"); - query = $"update romlist SET `Hash` = '{romhash}' where Id ={list[i].id}"; + string query = $"SELECT id,`Name`,GameType,Note,RomUrl,ImgUrl,`Hash` FROM romlist"; using (var command = new MySqlCommand(query, conn)) { // 执行查询并处理结果 - int reader = command.ExecuteNonQuery(); - if (reader > 0) - AppSrv.g_Log.Info($"第{i}个,处理成功"); - else - AppSrv.g_Log.Info($"第{i}个,处理失败"); + using (var reader = command.ExecuteReader()) + { + while (reader.Read()) + { + list.Add( + (reader.GetInt32(0), + !reader.IsDBNull(4) ? reader.GetString(4) : string.Empty, + !reader.IsDBNull(1) ? reader.GetString(1) : string.Empty + )); + } + } } + + for (int i = 0; i < list.Count; i++) + { + string rompath = Config.cfg.RomDir + "/" + list[i].romurl; + rompath = System.Net.WebUtility.UrlDecode(rompath); + if (!File.Exists(rompath)) + { + Nonelist.Add(list[i]); + continue; + } + string romhash = Helper.FileMD5Hash(rompath); + AppSrv.g_Log.Info($"第{i}个,Name->{list[i].name},Hash->{romhash}"); + query = $"update romlist SET `Hash` = '{romhash}' where Id ={list[i].id}"; + using (var command = new MySqlCommand(query, conn)) + { + // 执行查询并处理结果 + int reader = command.ExecuteNonQuery(); + if (reader > 0) + AppSrv.g_Log.Info($"第{i}个,处理成功"); + else + AppSrv.g_Log.Info($"第{i}个,处理失败"); + } + } + AppSrv.g_Log.Info($"处理完毕,共{Nonelist.Count}个文件没有找到"); + } + catch (Exception e) + { + AppSrv.g_Log.Info($"err:{e.ToString()}"); } - AppSrv.g_Log.Info($"处理完毕,共{Nonelist.Count}个文件没有找到"); } - catch (Exception e) - { - AppSrv.g_Log.Info($"err:{e.ToString()}"); - } - SQLPool.EnqueueSQLConn(conn); } } } \ No newline at end of file diff --git a/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile.pubxml.user b/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile.pubxml.user index 9e772c03..3359ad88 100644 --- a/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile.pubxml.user +++ b/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile.pubxml.user @@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. --> - True|2025-01-09T06:39:17.5797829Z||;True|2025-01-09T14:39:05.6042660+08:00||;True|2025-01-09T14:33:09.1944386+08:00||; + True|2025-02-25T02:21:20.8779432Z||;False|2025-02-25T10:20:39.1249758+08:00||;False|2025-02-24T23:48:17.6638177+08:00||;True|2025-01-09T14:39:17.5797829+08:00||;True|2025-01-09T14:39:05.6042660+08:00||;True|2025-01-09T14:33:09.1944386+08:00||; \ No newline at end of file diff --git a/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile1.pubxml.user b/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile1.pubxml.user index 9f1f3a0d..c3f8715b 100644 --- a/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile1.pubxml.user +++ b/AxibugEmuOnline.Server/Properties/PublishProfiles/FolderProfile1.pubxml.user @@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. --> - True|2025-01-13T08:07:43.4441316Z||;True|2025-01-09T15:02:05.2160606+08:00||;True|2025-01-09T14:48:42.5299550+08:00||;False|2025-01-09T14:48:02.6306184+08:00||;True|2025-01-09T14:17:00.2185117+08:00||;True|2025-01-08T23:13:47.7309044+08:00||;True|2025-01-08T13:32:52.0590130+08:00||;True|2025-01-08T13:31:56.8589678+08:00||;True|2025-01-07T13:54:02.0272718+08:00||;True|2025-01-07T10:47:36.6196477+08:00||;True|2025-01-07T01:21:34.5863249+08:00||;False|2025-01-07T01:20:39.5344134+08:00||;True|2025-01-07T00:21:47.4863058+08:00||;True|2025-01-07T00:16:42.7998249+08:00||;False|2025-01-07T00:16:02.8107509+08:00||;False|2025-01-02T15:36:18.1906464+08:00||;False|2025-01-02T15:36:06.5622643+08:00||;True|2024-12-27T18:24:49.7554320+08:00||; + True|2025-02-25T02:21:36.3766073Z||;True|2025-01-13T16:07:43.4441316+08:00||;True|2025-01-09T15:02:05.2160606+08:00||;True|2025-01-09T14:48:42.5299550+08:00||;False|2025-01-09T14:48:02.6306184+08:00||;True|2025-01-09T14:17:00.2185117+08:00||;True|2025-01-08T23:13:47.7309044+08:00||;True|2025-01-08T13:32:52.0590130+08:00||;True|2025-01-08T13:31:56.8589678+08:00||;True|2025-01-07T13:54:02.0272718+08:00||;True|2025-01-07T10:47:36.6196477+08:00||;True|2025-01-07T01:21:34.5863249+08:00||;False|2025-01-07T01:20:39.5344134+08:00||;True|2025-01-07T00:21:47.4863058+08:00||;True|2025-01-07T00:16:42.7998249+08:00||;False|2025-01-07T00:16:02.8107509+08:00||;False|2025-01-02T15:36:18.1906464+08:00||;False|2025-01-02T15:36:06.5622643+08:00||;True|2024-12-27T18:24:49.7554320+08:00||; \ No newline at end of file diff --git a/AxibugEmuOnline.Web/Common/SQLPool.cs b/AxibugEmuOnline.Web/Common/SQLPool.cs deleted file mode 100644 index 3dae9816..00000000 --- a/AxibugEmuOnline.Web/Common/SQLPool.cs +++ /dev/null @@ -1,202 +0,0 @@ -using Microsoft.Extensions.Logging; -using MySql.Data.MySqlClient; - -namespace AxibugEmuOnline.Web.Common -{ - public static class SQLPool - { - static Queue _ConQueue = new Queue(); - static Dictionary _OutOfSQLPool = new Dictionary(); - static Dictionary _DicSqlRunFunNum = new Dictionary(); - static Dictionary _DicTimeOutSqlRunFunNum = new Dictionary(); - const int DefaultCount = 1; - const int MaxLimit = 5; - static readonly object _sync = new object(); - static MySqlConnectionStringBuilder connBuilder; - - public static void InitConnMgr() - { - connBuilder = new MySqlConnectionStringBuilder(); - connBuilder.Database = Config.cfg.DBName; - connBuilder.Server = Config.cfg.DBIp; - connBuilder.UserID = Config.cfg.DBUname; - connBuilder.Password = Config.cfg.DBPwd; - connBuilder.Port = Config.cfg.DBPort; - //connBuilder.MinimumPoolSize = 40u; - //connBuilder.MaximumPoolSize = 100u; - connBuilder.Pooling = true; - - - Console.WriteLine("SQLPool连接初始化...."); - for (int i = 0; i < DefaultCount; i++) - { - MySqlConnection _conn = conn(); - _conn.Open(); - _ConQueue.Enqueue(_conn); - } - Console.WriteLine("SQLPool初始化完毕,连接数" + _ConQueue.Count); - } - public static MySqlConnection conn() - { - return new MySqlConnection(connBuilder.ConnectionString); - } - - public static MySqlConnection DequeueSQLConn(string FuncStr) - { - lock (_sync) - { - if (_DicSqlRunFunNum.ContainsKey(FuncStr)) - { - _DicSqlRunFunNum[FuncStr]++; - } - else - { - _DicSqlRunFunNum[FuncStr] = 1L; - } - MySqlConnection _conn = null; - if (_ConQueue.Count < 1) - { - Console.WriteLine("[DequeueSQLConn]创建新的SQLPool.Count>" + _ConQueue.Count); - _conn = conn(); - _conn.Open(); - } - else - { - MySqlConnection temp = null; - while (_ConQueue.Count > 0) - { - Console.WriteLine("[DequeueSQLConn]取出一个SQLCount.Count>" + _ConQueue.Count); - temp = _ConQueue.Dequeue(); - if (temp.State == System.Data.ConnectionState.Closed) - { - Console.WriteLine("[DequeueSQLConn]已经断开SQLCount.Count>" + _ConQueue.Count); - temp.Dispose(); - temp = null; - continue; - } - } - - if (temp != null) - { - _conn = temp; - } - else - { - Console.WriteLine("[DequeueSQLConn]连接池全部已断开,重新创建连接"); - _conn = conn(); - _conn.Open(); - } - } - - _OutOfSQLPool.Add(_conn, new Haoyue_PoolTime - { - time = time(), - FuncStr = FuncStr - }); - - return _conn; - } - } - public static void EnqueueSQLConn(MySqlConnection BackConn) - { - lock (_sync) - { - if (_OutOfSQLPool.ContainsKey(BackConn)) - { - _OutOfSQLPool.Remove(BackConn); - } - else - { - Console.WriteLine("出队遗漏的数据出现了!"); - } - if (_ConQueue.Count > MaxLimit) - { - Console.WriteLine("已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count); - BackConn.Close(); - BackConn.Dispose(); - BackConn = null; - } - else - { - _ConQueue.Enqueue(BackConn); - Console.WriteLine("回收SQLPool.Count>" + _ConQueue.Count); - } - } - } - - public static void CheckPoolTimeOut() - { - lock (_sync) - { - long now = time(); - List removeTemp = new List(); - foreach (KeyValuePair o2 in _OutOfSQLPool) - { - if (now - o2.Value.time >= 120) - { - if (_DicTimeOutSqlRunFunNum.ContainsKey(o2.Value.FuncStr)) - { - _DicTimeOutSqlRunFunNum[o2.Value.FuncStr]++; - } - else - { - _DicTimeOutSqlRunFunNum[o2.Value.FuncStr] = 1L; - } - if (_ConQueue.Count > MaxLimit) - { - Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "已经不需要回收了,多余了,SQLPool.Count>" + _ConQueue.Count); - o2.Key.Close(); - } - else - { - Console.WriteLine("[超时回收]" + o2.Value.FuncStr + "回收SQLPool.Count>" + _ConQueue.Count); - _ConQueue.Enqueue(o2.Key); - } - removeTemp.Add(o2.Key); - } - } - if (removeTemp.Count() <= 0) - { - return; - } - foreach (MySqlConnection o in removeTemp) - { - if (_OutOfSQLPool.ContainsKey(o)) - { - _OutOfSQLPool.Remove(o); - Console.WriteLine("[超时回收]_OutOfSQLPool清理"); - } - else - { - Console.WriteLine("[超时回收]_OutOfSQLPool清理异常???????"); - } - } - Console.WriteLine("[超时回收]处理结束SQLPool.Count>" + _ConQueue.Count); - } - } - public static long time() - { - return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds); - } - public static void GetPoolState() - { - Console.WriteLine("-----------------查询统计-----------------"); - foreach (KeyValuePair dic2 in _DicSqlRunFunNum) - { - Console.WriteLine(dic2.Key + ":" + dic2.Value); - } - Console.WriteLine("-----------------超时统计-----------------"); - foreach (KeyValuePair dic in _DicTimeOutSqlRunFunNum) - { - Console.WriteLine(dic.Key + ":" + dic.Value); - } - Console.WriteLine("------------------------------------------"); - } - } - - public class Haoyue_PoolTime - { - public long time { get; set; } - public string FuncStr { get; set; } - } -} diff --git a/AxibugEmuOnline.Web/Common/SQLRUN.cs b/AxibugEmuOnline.Web/Common/SQLRUN.cs new file mode 100644 index 00000000..3b5c4f89 --- /dev/null +++ b/AxibugEmuOnline.Web/Common/SQLRUN.cs @@ -0,0 +1,72 @@ +using MySql.Data.MySqlClient; + +namespace AxibugEmuOnline.Web.Common +{ + public static class SQLRUN + { + // 移除自定义队列和状态跟踪字典 + private static Dictionary _DicSqlRunFunNum = new Dictionary(); + private static Dictionary _DicTimeOutSqlRunFunNum = new Dictionary(); + + const int DefaultCount = 1; + const int MaxLimit = 10; + static readonly object _sync = new object(); + static MySqlConnectionStringBuilder connBuilder; + + public static void InitConnMgr() + { + // 配置 MySQL 内置连接池 + connBuilder = new MySqlConnectionStringBuilder + { + Database = Config.cfg.DBName, + Server = Config.cfg.DBIp, + UserID = Config.cfg.DBUname, + Password = Config.cfg.DBPwd, + Port = Config.cfg.DBPort, + Pooling = true, // 启用内置连接池 + MinimumPoolSize = DefaultCount, // 最小连接数 + MaximumPoolSize = MaxLimit // 最大连接数 + }; + + // 初始化时不手动创建连接,依赖连接池自动管理 + Console.WriteLine("SQLPool初始化完成,连接池参数已配置"); + } + + public static MySqlConnection GetConn(string FuncStr) + { + lock (_sync) + { + IncrementFuncCall(FuncStr); + // 直接使用 MySQL 内置连接池获取连接 + var conn = new MySqlConnection(connBuilder.ConnectionString); + conn.Open(); + return conn; + } + } + + public static void GetPoolState() + { + Console.WriteLine("-----------------查询统计-----------------"); + foreach (var entry in _DicSqlRunFunNum) + { + Console.WriteLine($"函数 {entry.Key} 调用次数: {entry.Value}"); + } + Console.WriteLine("-----------------超时统计-----------------"); + foreach (var entry in _DicTimeOutSqlRunFunNum) + { + Console.WriteLine($"函数 {entry.Key} 超时次数: {entry.Value}"); + } + Console.WriteLine("------------------------------------------"); + } + + #region 私有方法(辅助统计逻辑) + private static void IncrementFuncCall(string funcStr) + { + _DicSqlRunFunNum[funcStr] = _DicSqlRunFunNum.ContainsKey(funcStr) ? _DicSqlRunFunNum[funcStr] + 1 : 1; + } + + #endregion + + } + +} \ No newline at end of file diff --git a/AxibugEmuOnline.Web/Controllers/ApiController.cs b/AxibugEmuOnline.Web/Controllers/ApiController.cs index 1a6e16ca..86525b62 100644 --- a/AxibugEmuOnline.Web/Controllers/ApiController.cs +++ b/AxibugEmuOnline.Web/Controllers/ApiController.cs @@ -65,7 +65,7 @@ namespace AxibugEmuOnline.Web.Controllers Resp_GameList resp = new Resp_GameList(); resp.gameList = new List(); - MySqlConnection conn = SQLPool.DequeueSQLConn("RomList"); + using (MySqlConnection conn = SQLRUN.GetConn("RomList")) { List condition = new List(); @@ -168,7 +168,6 @@ namespace AxibugEmuOnline.Web.Controllers } } } - SQLPool.EnqueueSQLConn(conn); } return new JsonResult(resp); } @@ -200,7 +199,7 @@ namespace AxibugEmuOnline.Web.Controllers string searchPattern = $"%{SearchKey}%"; Resp_GameList resp = new Resp_GameList(); resp.gameList = new List(); - MySqlConnection conn = SQLPool.DequeueSQLConn("MarkList"); + using (MySqlConnection conn = SQLRUN.GetConn("MarkList")) { string platformCond = ""; if (Ptype > (int)RomPlatformType.Invalid && Ptype < (int)RomPlatformType.All) @@ -297,7 +296,6 @@ LIMIT ?offset, ?pageSize;"; } } } - SQLPool.EnqueueSQLConn(conn); } return new JsonResult(resp); } @@ -313,7 +311,7 @@ LIMIT ?offset, ?pageSize;"; string searchPattern = $"%{RomInfo}%"; Resp_RomInfo resp = new Resp_RomInfo(); - MySqlConnection conn = SQLPool.DequeueSQLConn("NesRomList"); + using (MySqlConnection conn = SQLRUN.GetConn("NesRomList")) { string query = $"SELECT id,`Name`,GameType,Note,RomUrl,ImgUrl,`Hash`,`playcount`,`stars`,`PlatformType`,`parentids` FROM romlist where id = ?romid;"; using (var command = new MySqlCommand(query, conn)) @@ -347,7 +345,6 @@ LIMIT ?offset, ?pageSize;"; } } } - SQLPool.EnqueueSQLConn(conn); } if (UID > 0) @@ -385,24 +382,25 @@ LIMIT ?offset, ?pageSize;"; public bool CheckIsRomStar(int RomId, long uid) { bool bhad = false; - MySqlConnection conn = SQLPool.DequeueSQLConn("CheckIsRomStart"); - try + using (MySqlConnection conn = SQLRUN.GetConn("CheckIsRomStart")) { - string query = $"SELECT count(0) from rom_stars where uid = ?uid and romid = ?romid"; - using (var command = new MySqlCommand(query, conn)) + try { - // òֵ - command.Parameters.AddWithValue("?romid", RomId); - command.Parameters.AddWithValue("?uid", uid); - // ִвѯȡ - bhad = (int)command.ExecuteScalar() > 0; + string query = $"SELECT count(0) from rom_stars where uid = ?uid and romid = ?romid"; + using (var command = new MySqlCommand(query, conn)) + { + // òֵ + command.Parameters.AddWithValue("?romid", RomId); + command.Parameters.AddWithValue("?uid", uid); + // ִвѯȡ + bhad = (int)command.ExecuteScalar() > 0; + } + } + catch (Exception e) + { + //AppSrv.g_Log.Error(e); } } - catch (Exception e) - { - //AppSrv.g_Log.Error(e); - } - SQLPool.EnqueueSQLConn(conn); return bhad; } diff --git a/AxibugEmuOnline.Web/Properties/PublishProfiles/FolderProfile.pubxml.user b/AxibugEmuOnline.Web/Properties/PublishProfiles/FolderProfile.pubxml.user index e660ae9e..80c2e812 100644 --- a/AxibugEmuOnline.Web/Properties/PublishProfiles/FolderProfile.pubxml.user +++ b/AxibugEmuOnline.Web/Properties/PublishProfiles/FolderProfile.pubxml.user @@ -5,7 +5,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. <_PublishTargetUrl>G:\Sin365\AxibugEmuOnline\AxibugEmuOnline.Web\bin\Release\net8.0\publish\ - True|2025-02-05T03:59:16.6277678Z||;True|2025-02-05T11:57:28.8928988+08:00||;True|2025-01-23T14:10:54.0851574+08:00||;True|2025-01-23T13:21:13.2937446+08:00||;True|2025-01-23T13:15:40.1876887+08:00||;True|2025-01-13T15:57:42.8554189+08:00||;True|2025-01-13T15:56:16.9992929+08:00||;True|2025-01-09T15:00:13.8691822+08:00||;True|2025-01-09T14:47:16.4993283+08:00||;True|2025-01-09T14:47:09.3814423+08:00||;True|2025-01-09T14:38:36.2730244+08:00||;True|2025-01-08T13:35:26.6793825+08:00||;True|2025-01-07T10:37:18.6461694+08:00||;True|2024-09-12T14:18:38.6992653+08:00||;True|2024-09-12T14:08:58.4526827+08:00||;True|2024-08-22T14:13:06.3067002+08:00||;True|2024-08-14T10:33:10.9180984+08:00||;True|2024-08-13T18:28:27.5050523+08:00||;True|2024-08-13T18:25:47.6591234+08:00||;True|2024-08-13T18:25:17.5344107+08:00||;True|2024-08-13T17:46:23.4523329+08:00||; + True|2025-02-25T02:10:20.1998665Z||;True|2025-02-25T10:06:10.7381658+08:00||;True|2025-02-24T20:17:30.7705009+08:00||;True|2025-02-24T20:17:22.8138039+08:00||;True|2025-02-24T20:04:18.6428884+08:00||;True|2025-02-24T20:03:59.5011548+08:00||;True|2025-02-24T19:53:21.4793388+08:00||;True|2025-02-05T11:59:16.6277678+08:00||;True|2025-02-05T11:57:28.8928988+08:00||;True|2025-01-23T14:10:54.0851574+08:00||;True|2025-01-23T13:21:13.2937446+08:00||;True|2025-01-23T13:15:40.1876887+08:00||;True|2025-01-13T15:57:42.8554189+08:00||;True|2025-01-13T15:56:16.9992929+08:00||;True|2025-01-09T15:00:13.8691822+08:00||;True|2025-01-09T14:47:16.4993283+08:00||;True|2025-01-09T14:47:09.3814423+08:00||;True|2025-01-09T14:38:36.2730244+08:00||;True|2025-01-08T13:35:26.6793825+08:00||;True|2025-01-07T10:37:18.6461694+08:00||;True|2024-09-12T14:18:38.6992653+08:00||;True|2024-09-12T14:08:58.4526827+08:00||;True|2024-08-22T14:13:06.3067002+08:00||;True|2024-08-14T10:33:10.9180984+08:00||;True|2024-08-13T18:28:27.5050523+08:00||;True|2024-08-13T18:25:47.6591234+08:00||;True|2024-08-13T18:25:17.5344107+08:00||;True|2024-08-13T17:46:23.4523329+08:00||; \ No newline at end of file