using Chloe;
using Chloe.Infrastructure;
using Chloe.SqlServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
///
public class DBconnectionManagement
{
public DBconnectionManagement() {
aconnList = new List<DbObject>();
aLock = new object();
}
private List<DbObject> aconnList { get; set; }
/// <summary>
/// 获去一个新的连接
/// </summary>
/// <returns></returns>
private MyDbContext getNewconn()
{
return new MyDbContext("data source=119.29.21.XXX;initial catalog=XXX;user id=XX;password=XXX");
}
/// <summary>
/// 新增一个连接到队列中
/// </summary>
private void Addconn() {
aconnList.Add(new DbObject(getNewconn()));
Console.WriteLine("新增了一个连接对象 目前" + aconnList.Count);
}
int getCount = 0;
object aLock { get; set; }
/// <summary>
/// 获取一个连接对象
/// </summary>
public IDbContext Getconn()
{
Console.WriteLine("获取一次 第"+ ++getCount);
IDbContext result;
lock (aLock)
{
result = aconnList.Where(d => d.IsUse == false).Select(d => d.Conn).FirstOrDefault();
}
if (result == null)
{
Addconn();
return Getconn();
}
return result;
}
}
/// <summary>
/// 存放DB对象
/// </summary>
public class DbObject {
private DbObject() { }
public DbObject(MyDbContext conn) {
conn.ABackOffFunc += BackOffFunc;
this.Conn = conn;
this.IsUse = false;
}
/// <summary>
/// 连接对象
/// </summary>
private MyDbContext conn { get; set; }
/// <summary>
/// 连接对象
/// </summary>
public MyDbContext Conn { get { IsUse = true;return conn; } set { conn = value; } }
/// <summary>
/// 是否真正被使用
/// </summary>
public bool IsUse { get; set; }
/// <summary>
/// 销毁时候的回掉函数
/// </summary>
public Action<DbObject> AFuncComplete;
private void BackOffFunc(MyDbContext conn) {
AFuncComplete?.Invoke(this);
IsUse = false;
}
}
/// <summary>
/// 重写的连接对象
/// </summary>
public class MyDbContext : MsSqlContext, IDisposable {
public MyDbContext(string connString):base(connString) {
}
public MyDbContext(IDbConnectionFactory dbConnectionFactory) : base(dbConnectionFactory) {
}
public new void Dispose()
{
ABackOffFunc.Invoke(this);
}
/// <summary>
/// 真实销毁函数
/// </summary>
public void Close() {
//如果不执行此操作将会一直保持连接 可以使用定时器销毁对象
base.Dispose();
}
/// <summary>
/// 销毁时候的回掉函数
/// </summary>
public Action<MyDbContext> ABackOffFunc;
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章