有没有标准连接池模型(或API)类似于所使用的.net 中的数据提供者我可以用它来实现我自己的连接池吗?
我之所以这么问,是因为我需要将自己的连接池实现到我们在 Web 服务中使用的专有 TCP/IP 设备。当前的问题是,由于 IIS 下运行的 Web 服务的线程特性,设备有大量连接(读取太多)。我想使用自己的连接池来限制这些连接的数量,如果有一个我可以用来做到这一点的标准模型,那么重新发明轮子似乎很愚蠢。
是否有标准的连接池模型
除了 ADO.NET 之外,没有。但 ADO.NET 模型非常简单。构造一个对象以从池中获取连接,或重新创建一个对象,并在 Close/Dispose/Finalise 时将其返回到池中。
由此可以立即确定一种实现模式:
- 客户端类型是真实类型的代理,并且具有从创建到结束的生命周期
关闭/…。它是真实对象的代理。提供方法和属性
转发到真正的连接。
- 真正的连接是一个长期存在的实例,由池创建,在代理下发出
然后在代理结束时返回。
在实施过程中有一个选择。当对象被分发后,池是否还需要保留引用?如果确实如此,池需要跟踪哪些对象是活动的以及哪些对象被池化;否则可以使用可用对象的简单集合。
就像是:
internal class MyObjectImpl {
// The real object that holds the resource
}
internal static class MyObjectPool {
private static object syncRoot = new object();
private static Queue<MyObjectImpl> pool = new Queue<MyObject>();
private static int totalObjects = 0;
private readonly int maxObjects = 10;
internal MyObjectImplGet() {
lock (syncRoot) {
if (pool.Count > 0) {
return pool.Dequeue();
}
if (totalObjects >= maxObjects) {
throw new PoolException("No objects available");
}
var o = new MyObjectImpl();
totalObjects++;
return o;
}
}
internal void Return(MyObjectImpl obj) {
lock (syncRoot) {
pool.Enqueue(obj);
}
}
}
public class MyObject : IDisposable {
private MyObjectImpl impl;
public MyObject() {
impl = MyObjectPool.Get();
}
public void Close() {
Dispose();
}
public void Dispose() {
MyIObjectPool.Return(impl);
// Prevent continuing use, as the implementation object instance
// could now be given out.
impl = null;
}
// Forward API to implement
}
This doesn't cater for instances of MyObject
being destroyed. E.g. hold a collection of weak references to allocated MyObject
's, and if the pool is empty check for disposed instances. This would also be needed if you cannot rely on client's to Close or dispose of instances, or implement a finaliser on MyObjectImpl
1 (and report this as an error in debug builds).
1 This cannot be done on MyObject because by the time MyObject was finalised the MyObjectImpl instance could already have been finalised.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)