usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Timers;namespaceCommonAssistant
{public classMySqlConnectionPool
{private readonly string sqlConnect = string.Empty;public MySqlConnectionPool(stringConnection)
{
sqlConnect=Connection;//定时器轮询连接,清理不在使用的连接
var timer = newTimer();
timer.Enabled= true;
timer.Elapsed+= (a, b) =>{//轮询连接池连接,删除满足条件的连接
delwithConnectPool("remove");
Console.WriteLine("连接数:"+getCount());
};
timer.Interval= 1000 * 10; //10分钟一次
timer.AutoReset = true;//一直执行
}private static List listConnects = new List();private static readonly object obj_getConnects = new object();public Tuple delwithConnectPool(stringtype)
{//保证并发条件下集合增删改查时的数据唯一性
lock(obj_getConnects)
{bool result = false;
ConnectionItem result_item= null;switch(type)
{case "get":var connectItem = listConnects.Where(u => u.ifBusy == false).FirstOrDefault();if (connectItem == null)
{
listConnects.Add(result_item=getInstance(sqlConnect));
}else{if (connectItem.mySqlConn.State ==System.Data.ConnectionState.Open)
{
connectItem.setBusy(true);
connectItem.updateTime(DateTime.Now);
result_item=connectItem;
}else{
listConnects.Add(result_item=getInstance(sqlConnect));
}
}break;case "remove":if (listConnects != null &&listConnects.Any())
{//删除移除 超过10分钟未使用的的连接,使用两分钟的未释放连接,连接状态已关闭的连接
var listOuteTimes = listConnects.Where(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > 120) || ((DateTime.Now - u.time).TotalSeconds > 60 * 10) ||(u.mySqlConn.State !=System.Data.ConnectionState.Open) );foreach (var item inlistOuteTimes)
{
item.mySqlConn.Close();
item.mySqlConn.Dispose();//释放
}//超时连接移除
listConnects.RemoveAll(u => (u.ifBusy == true && (DateTime.Now - u.time).TotalSeconds > 120) || ((DateTime.Now - u.time).TotalSeconds > 60 * 10) || (u.mySqlConn.State !=System.Data.ConnectionState.Open));
}break;
}return new Tuple(result, result_item);
}
}public ConnectionItem getInstance(stringconnect)
{var item = newConnectionItem()
{
ifBusy= true,
time=DateTime.Now,
mySqlConn= newMySqlConnection(connect)
};
item.mySqlConn.Open();returnitem;
}//获取一个空闲连接
publicConnectionItem getFreeConnectItem()
{return delwithConnectPool("get").Item2;
}public intgetCount() {returnlistConnects.Count;
}
}public classConnectionItem : IDisposable
{public DateTime time { get; set; }public MySqlConnection mySqlConn { get; set; }public bool ifBusy { get; set; }//设置是否在使用
public void setBusy(boolbusy)
{
ifBusy=busy;
}public voidupdateTime(DateTime dt)
{
time=dt;
}public voidDispose()
{
ifBusy= false;
}
}
}