如果你使用过或正在使用IOC/DI容器,那么这对你了解和熟悉组件的生命周期将是非常有用的。
通常情况下,建议将ElasticClient
实例注册为一个单例,因为ElasticClient
客户端是线程安全的,因此跨线程共享实例是没问题的。单例最大的好处是会为每个ConnectionSettings
建立缓存。
但在某些应用程序中,也有可能会为不能的ConnectionSettings
创建不同的ElasticClient
实例,因为应用程序可能连接两个不同的Elasticsearch集群。
特别注意:由于Elasticsearch的语义版本控制,Elasticsearch.Net、NEST及其Elasticsearch版本,所有连接到的ElasticClient和Elasticsearch集群的实例必须在同一个主版本上。
下面通过创建派生于ConnectionSettings
、IConnectionPool
和IConnection
等类型来演示哪些组件会被释放:
private class AConnectionSettings : ConnectionSettings
{
public AConnectionSettings(IConnectionPool pool, IConnection connection)
: base(pool, connection)
{ }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
private class AConnectionPool : SingleNodeConnectionPool
{
public AConnectionPool(Uri uri, IDateTimeProvider dateTimeProvider = null) : base(uri, dateTimeProvider) { }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
private class AConnection : InMemoryConnection
{
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
ConnectionSettings
、IConnectionPool
和IConnection
都显式地实现了IDisposable
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
settings.IsDisposed.Should().BeFalse();
connectionPool.IsDisposed.Should().BeFalse();
connection.IsDisposed.Should().BeFalse();
释放一个ConnectionSettings
同时也会释放它使用到的IConnectionPool
和IConnection
实例
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
using (settings) { } // 使用using来强制释放using块中的资源
settings.IsDisposed.Should().BeTrue();
connectionPool.IsDisposed.Should().BeTrue();
connection.IsDisposed.Should().BeTrue();
发表评论
登录用户才能发表评论, 请 登 录 或者 注册