有没有一种编程方法可以找到当前由.Net连接器/MySql.Data.dll维护的数据库打开连接的数量?
我感兴趣的是在使用库的同一个程序中收集这些信息。
发布于 2013-02-20 01:53:57
连接池是在客户端执行的。要访问它,需要使用反射来访问MySqlPoolManager和MySqlPool类,这两个类都是MySql.Data程序集的内部类。
从本质上讲,您需要使用反射来访问池。下面是操作步骤:
Assembly ms = Assembly.LoadFrom("MySql.Data.dll");
Type type = ms.GetType("MySql.Data.MySqlClient.MySqlPoolManager");
MethodInfo mi = type.GetMethod("GetPool", BindingFlags.Static | BindingFlags.Public);
var pool = mi.Invoke(null, new object[] { new MySqlConnectionStringBuilder(connString) });您会注意到,您必须传入一个MySqlConnectionStringBuilder对象。它为每个连接字符串创建一个单独的池,因此使用与应用程序中使用的相同的连接字符串(它需要完全相同)。
然后,您可以访问私有池字段和属性(同样,使用反射),以获取所需的信息。特别是,您可能会对"available“字段和"NumConnections”属性感兴趣。还有"idlePool“(一个Queue<>)和"inUsePool”(一个List<>),您也可以访问它们,特别是计数。
发布于 2018-06-15 16:51:21
多亏了Petes answer to this question和this other answer,我才能构建下面的函数:
/// <returns>totalAvailable, inUseCount, idleCount</returns>
public int[] GetPoolStatsViaReflection(MySqlConnectionStringBuilder connectionStringBuilder)
{
var asm = typeof(MySqlConnectionStringBuilder).Assembly;
var poolManagerType = asm.GetType("MySql.Data.MySqlClient.MySqlPoolManager"); // internal sealed
var poolType = asm.GetType("MySql.Data.MySqlClient.MySqlPool"); // internal sealed
var pool = poolManagerType.InvokeMember("GetPool", System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, null, new object[] { connectionStringBuilder });
const System.Reflection.BindingFlags nonPublicInstanceField = System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
var totalAvailable = (int)poolType.InvokeMember("available", nonPublicInstanceField, null, pool, new object[] { });
// List<Driver>
var inUsePool = (System.Collections.ICollection)poolType.InvokeMember("inUsePool", nonPublicInstanceField, null, pool, new object[] { });
// Queue<Driver>
var idlePool = (System.Collections.ICollection)poolType.InvokeMember("idlePool", nonPublicInstanceField, null, pool, new object[] { });
return new[] {totalAvailable, inUsePool.Count, idlePool.Count};
}https://stackoverflow.com/questions/14963556
复制相似问题