避免ElasticSearch错误503服务器不可用:使用WaitForStatus

问题描述 投票:0回答:1

启动程序时,我运行ElasticSearch服务并检查索引是否存在并且是否有任何文档,假设我只是运行ES服务,并且具有以下两个功能:

public ElasticClient getElasticSearchClient()
{
    ConnectionSettings connectionSettings = new Nest.ConnectionSettings(new Uri("http://localhost:9200"))
                                                    .DefaultIndex("myindex")
                                                    .DisableDirectStreaming();
    ElasticClient client = new ElasticClient(connectionSettings);
    //var health = client.Cluster.Health("myindex", a => (a.WaitForStatus(WaitForStatus.Yellow)).Timeout(50));
    return client;
}

public void checkElasticsearchIndex()
{
    var client = getElasticSearchClient();

    var health = this.client.Cluster.Health("myindex", a => (a.WaitForStatus(WaitForStatus.Yellow)));

    CountResponse count = client.Count<myobject>();

    if (!client.Indices.Exists("myindex").IsValid || count.Count == 0)
    {
        BulkWriteAllToIndexES(client);
    }
}

在checkElasticsearchIndex函数内部,

  1. 计数操作失败,并显示以下错误消息:

    OriginalException:Elasticsearch.Net.ElasticsearchClientException:远程服务器返回错误:(503)服务器不可用。.调用:状态码503,来自:GET / myindex / _count。 ServerError:类型:search_phase_execution_exception原因:“所有分片均失败” ---> System.Net.WebException:远程服务器返回错误:(503)服务器不可用。

  2. 健康同样失败:

    OriginalException:Elasticsearch.Net.ElasticsearchClientException:无法连接到远程服务器。呼叫:状态代码未知:GET / _cluster / health / myindex?wait_for_status =黄色---> System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:无法建立连接因为目标计算机主动拒绝它而被执行127.0.0.1:9200

您可以看到,我已经尝试了集群WaitForStatus,但是没有用。

我的问题:有什么办法可以等到客户端/集群/节点准备好并且没有收到任何异常?

c# elasticsearch nest elasticsearch-7
1个回答
0
投票
听起来您在启动程序的同时正在启动Elasticsearch进程,但是Elasticsearch花费比准备程序更长的时间。

如果是这种情况,您可能会对使用.NET客户端用于针对Elasticsearch的集成测试的the same abstractions感兴趣。抽象从Elasticsearch进程中读取输出,以知道何时准备就绪,并阻塞直到发生这种情况。有available on an AppVeyor CI package feed(并计划在将来将其发布给Nuget)。

some examples of how to spin up a cluster with the abstractions。对于单个节点,它将类似于

using System; using Elastic.Managed.Configuration; using Elastic.Managed.ConsoleWriters; using Elastic.Managed.FileSystem; namespace Elastic.Managed.Example { class Program { static void Main(string[] args) { var version = "7.5.1"; var esHome = Environment.ExpandEnvironmentVariables($@"%LOCALAPPDATA%\ElasticManaged\{version}\elasticsearch-{version}"); using (var node = new ElasticsearchNode(version, esHome)) { node.SubscribeLines(new LineHighlightWriter()); if (!node.WaitForStarted(TimeSpan.FromMinutes(2))) throw new Exception(); // do your work here } } } }

这假设Elasticsearch 7.5.1 zip已经下载,并且位于%LOCALAPPDATA%\ElasticManaged\7.5.1\elasticsearch-7.5.1。还有更复杂的examples of how to integrate this into tests with xUnit.

您可以use the EphemeralCluster components下载,配置和运行Elasticsearch

EphemeralCluster

© www.soinside.com 2019 - 2024. All rights reserved.