[Fact] public void StaticPoolWithstandsConcurrentReadAndWrites() { var uris = Enumerable.Range(9200, _numberOfNodes).Select(p => new Uri("http://localhost:" + p)); var staticPool = new StaticConnectionPool(uris, false); Action callStatic = () => AssertCreateView(staticPool); callStatic.Should().NotThrow(); }
public ExampleTest(TestCluster cluster) { this.Client = cluster.GetOrAddClient(c => { var nodes = cluster.NodesUris(); var connectionPool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(connectionPool).EnableDebugMode(); return(new ElasticClient(settings)); }); }
public ElasticAccess(string connString) { var pool = new StaticConnectionPool(connString.Split(',').Select(uri => new Uri(uri))); var settings = new ConnectionSettings(pool); settings.DisableDirectStreaming(); client = new ElasticClient(settings); }
[U] public void EachViewStartsAtNexPositionAndWrapsOver() { var uris = Enumerable.Range(9200, NumberOfNodes).Select(p => new Uri("http://localhost:" + p)); var staticPool = new StaticConnectionPool(uris, randomize: false); var sniffingPool = new SniffingConnectionPool(uris, randomize: false); this.AssertCreateView(staticPool); this.AssertCreateView(sniffingPool); }
private ElasticClient SetupElasticSearch() { var nodes = new Uri[] { new Uri("http://localhost:9200") // new Uri("http://ipv4.fiddler:9200") //use fiddler to see messages to & from elasticsearch }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings( pool, new HttpConnection(), new SerializerFactory((jsonSettings, nestSettings) => jsonSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore) ); /**** * USE THE FOLLOWING CODE to DEBUG or LOG without Fiddler * var list = new List<string>(); * * settings * .DisableDirectStreaming() * .DisableAutomaticProxyDetection(true) * .OnRequestCompleted(response => * { * // log out the request and the request body, if one exists for the type of request * if (response.RequestBodyInBytes != null) * { * list.Add( * $"{response.HttpMethod} {response.Uri} \n" + * $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}"); //this is where the request JSON will go * } * else * { * list.Add($"{response.HttpMethod} {response.Uri}"); * } * * // log out the response and the response body, if one exists for the type of response * if (response.ResponseBodyInBytes != null) * { * list.Add($"Status: {response.HttpStatusCode}\n" + * $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" + * $"{new string('-', 30)}\n"); * } * else * { * list.Add($"Status: {response.HttpStatusCode}\n" + * $"{new string('-', 30)}\n"); * } * }); ****/ var client = new ElasticClient(settings); return(client); }
private static void ManualConfigRun() { ElasticVersion version = "latest"; var plugins = new ElasticsearchPlugins(ElasticsearchPlugin.IngestGeoIp, ElasticsearchPlugin.IngestAttachment); var features = Security | XPack | SSL; var config = new EphemeralClusterConfiguration(version, features, plugins, numberOfNodes: 1) { HttpFiddlerAware = true, ShowElasticsearchOutputAfterStarted = true, CacheEsHomeInstallation = false, TrialMode = XPackTrialMode.Trial, NoCleanupAfterNodeStopped = false, }; using (var cluster = new EphemeralCluster(config)) { cluster.Start(); var nodes = cluster.NodesUris(); var connectionPool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(connectionPool).EnableDebugMode(); if (config.EnableSecurity) { settings = settings.BasicAuthentication(ClusterAuthentication.Admin.Username, ClusterAuthentication.Admin.Password); } if (config.EnableSsl) { settings = settings.ServerCertificateValidationCallback(CertificateValidations.AllowAll); } var client = new ElasticClient(settings); var clusterConfiguration = new Dictionary <string, object>() { { "cluster.routing.use_adaptive_replica_selection", true }, { "cluster.remote.remote-cluster.seeds", "127.0.0.1:9300" } }; var putSettingsResponse = client.ClusterPutSettings(new ClusterPutSettingsRequest { Transient = clusterConfiguration }); Console.Write(client.XPackInfo().DebugInformation); Console.WriteLine("Press any key to exit"); Console.ReadKey(); Console.WriteLine("Exitting.."); } Console.WriteLine("Done!"); }
private static ElasticClient CreateClient(EphemeralCluster cluster) { var nodes = cluster.NodesUris(); var connectionPool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(connectionPool) //.Proxy(new Uri("http://localhost:8080"), "", "") .EnableDebugMode(); return(new ElasticClient(settings)); }
private static IElasticClient GetElasticClient(ElasticSearchConfiguration elasticConfiguration) { var pool = new StaticConnectionPool(elasticConfiguration.EsNodeUris); var settings = new ConnectionSettings(pool).DefaultIndex(elasticConfiguration.EsIndex) .DefaultMappingFor <DummyDoc>(m => m.IndexName(elasticConfiguration.EsIndex).TypeName(typeof(DummyDoc).Name)) .EnablePrometheus(); // Enable Prometheus instrumentation return(new ElasticClient(settings)); }
/// <summary> /// 创建连接设置实例 /// </summary> /// <returns></returns> public static ConnectionSettings CreateInstance() { var connectPool = new StaticConnectionPool(Nodes); return(new ConnectionSettings(connectPool) .DefaultIndex(Constant.DefaultIndex) .RequestTimeout(TimeSpan.FromMinutes(2)) .EnableHttpCompression() .PrettyJson()); }
protected override void InitializeTarget() { base.InitializeTarget(); var uri = GetConnectionString(ConnectionStringName) ?? Uri; var nodes = uri.Split(',').Select(url => new Uri(url)); var connectionPool = new StaticConnectionPool(nodes); var config = new ConnectionConfiguration(connectionPool); _client = new ElasticsearchClient(config, serializer:ElasticsearchSerializer); }
public ESSever(IConfiguration configuration, IMemoryCache memoryCache_arg) { memoryCache = memoryCache_arg; var uris = configuration["ElasticSearchContext:Url"].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(x => new Uri(x)); var connectionPool = new StaticConnectionPool(uris); var settings = new ConnectionSettings(connectionPool).RequestTimeout(TimeSpan.FromSeconds(30));//.BasicAuthentication("elastic", "n@@W#RJQ$z1#") this.ElasticJsonClient = new ElasticLowLevelClient(settings); this.ElasticLinqClient = new ElasticClient(settings); }
public static ElasticClient ElasticClient(string defaultIndex) { var connectionPool = new StaticConnectionPool(GetUris()); var connectionSettings = new ConnectionSettings(connectionPool).DisableDirectStreaming(); connectionSettings.BasicAuthentication("elastic", "password"); // into a config..... var elasticClient = new ElasticClient(connectionSettings.DefaultIndex(defaultIndex)); return(elasticClient); }
/// <summary> /// 构造 /// </summary> /// <param name="url"></param> public EsClient(string nodeid, string url) { nodeId = nodeid; var uris = url.Split(",").ToList().ConvertAll(x => new Uri(x)); var connectionPool = new StaticConnectionPool(uris); var settings = new ConnectionConfiguration(connectionPool).RequestTimeout(TimeSpan.FromSeconds(30)); this.client = new ElasticLowLevelClient(settings); }
public static IElasticClient GetOrAddClient(this IEphemeralCluster cluster) { return(Clients.GetOrAdd(cluster, (c) => { var connectionPool = new StaticConnectionPool(c.NodesUris()); var settings = new ConnectionSettings(connectionPool); var client = new ElasticClient(settings); return client; })); }
public void AllNodesWillBeMarkedDead() { using (var fake = new AutoFake(callsDoNothing: true)) { //set up a fake datetimeprovider var dateTimeProvider = fake.Resolve <IDateTimeProvider>(); fake.Provide(dateTimeProvider); //create a connectionpool that uses the fake datetimeprovider var connectionPool = new StaticConnectionPool( _uris, dateTimeProvider: dateTimeProvider ); var config = new ConnectionConfiguration(connectionPool); fake.Provide <IConnectionConfigurationValues>(config); //Now() on the fake still means Now() A.CallTo(() => dateTimeProvider.Now()).Returns(DateTime.UtcNow); //Set up individual mocks for each DeadTime(Uri uri,...) call //where uri matches one of the node ports var calls = _uris.Select(u => A.CallTo(() => dateTimeProvider.DeadTime( A <Uri> .That.Matches(uu => uu.Port == u.Port), A <int> ._, A <int?> ._, A <int?> ._ ))).ToList(); //all the fake mark dead calls return 60 seconds into the future foreach (var call in calls) { call.Returns(DateTime.UtcNow.AddSeconds(60)); } //When we do a GET on / we always recieve a 503 var getCall = A.CallTo(() => fake.Resolve <IConnection>().GetSync(A <Uri> ._, A <IRequestConfiguration> ._)); getCall.Returns(_bad); var transport = this.ProvideTransport(fake); var pingCall = FakeCalls.PingAtConnectionLevel(fake); pingCall.Returns(_ok); var client = fake.Resolve <ElasticsearchClient>(); //Since we always get a 503 we should see an out of nodes exception Assert.Throws <MaxRetryException>(() => client.Info()); pingCall.MustHaveHappened(Repeated.Exactly.Times(4)); //The call should be tried on all the nodes getCall.MustHaveHappened(Repeated.Exactly.Times(4)); //We should see each individual node being marked as dead foreach (var call in calls) { call.MustHaveHappened(Repeated.Exactly.Once); } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient <IEmailSender, EmailSender>(); services.AddMvc(); AutoMapper.Mapper.Initialize(c => c.AddProfile <ILanni.FarmMarket.Repository.Mongo.AutoMapperProfile>()); Elasticsearch.Net.StaticConnectionPool pool = new StaticConnectionPool(new[] { new Uri("http://localhost:9200") }); ConnectionSettings estSettings = new ConnectionSettings(pool); estSettings.BasicAuthentication("elastic", "123456"); estSettings.InferMappingFor <Models.Product>(d => d.IdProperty(p => p.Id).IndexName("product").TypeName("product")); ElasticClient client = new ElasticClient(estSettings); services.AddSingleton <ElasticClient>(client); MongoClientSettings mSettings = new MongoClientSettings() { Credential = MongoCredential.CreateCredential("admin", "sa", "1"), Server = new MongoServerAddress("127.0.0.1", 27017), }; MongoClient mClient = new MongoClient(mSettings); services.AddSingleton <MongoClient>(mClient); services.AddSingleton <ILanni.FarmMarket.MQ.Settings>(new ILanni.FarmMarket.MQ.Settings()); var rmqConnFactory = new RabbitMQ.Client.ConnectionFactory() { UserName = "******", Password = "******" }; services.AddSingleton <RabbitMQ.Client.ConnectionFactory>(rmqConnFactory); PoolingSettings mqSetting = new PoolingSettings() { MaxChannelPerConnection = 5, MaxConnections = 2 }; ChannelPool channelPool = new ChannelPool(rmqConnFactory, mqSetting); services.AddSingleton(channelPool); services.AddScoped <ProductRepository>(); services.AddScoped <ProductPublisher>(); services.AddScoped <ProductService>(); }
static void Test() { var nodes = new Uri[] { new Uri("http://10.204.124.222:9200"), }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool).DefaultIndex("photo_album_image"); var client = new ElasticClient(settings); var lowLevelClient = new ElasticLowLevelClient(settings); var data = new ImageModel { Description = " 说明 ", CreateTime = DateTime.Now, Filename = "filename.jpng", KeyWorld = new System.Collections.Generic.List <string> { "test" }, Id = Guid.NewGuid().ToString(), Location = "shengzheng", Subject = "有望", Videos = "test.mp4" }; var ndexResponse = lowLevelClient.Index <ImageModel>("索引", "PostData", PostData.Serializable(data)); var searchResponse = lowLevelClient.Search <StringResponse>("people", PostData.Serializable(new { from = 0, size = 10, query = new { match = new { firstName = new { query = "Martijn" } } } })); var successful = searchResponse.Success; var responseJson = searchResponse.Body; var response = client.IndexDocument(data); var t = response.Result; var searchReponse = client.Search <ImageModel>(s => s.From(0).Size(10).Query(q => q. Match(m => m.Field(f => f.Filename).Query("filename.jpng")))); var people = searchReponse.Documents; }
protected StaticConnectionPool GetElasticPool() { // Get the elastic nodes var nodeUris = _indexNodes.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var nodes = nodeUris.Select(u => new Uri(u)).ToList(); // Create the elastic pool var pool = new StaticConnectionPool(nodes); return(pool); }
public static void LoadData() { var nodes = new List <Uri> { new Uri("http://*****:*****@"C:\cities_canada-usa.csv")) { if (!reader.EndOfStream) { reader.ReadLine(); } var documents = new List <City>(); while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(';'); //0 - id //1 - name //3 - alt_name //4 - lat //5 - lon //8 - country_code documents.Add(new City { Id = int.Parse(values[0]), Name = values[1], AltName = values[3], Country = values[8], Location = new Location(double.Parse(values[4]), double.Parse(values[5])), FullText = string.Concat(values[1], ", ", values[8]) }); } var result = client.IndexMany(documents, "city"); } }
/// <summary> /// 创建ElasticClient实例 /// </summary> private ElasticClient CreateEcInstance() { if (null == _elasticClient) { var lstUrls = _config.Server.Split(',').Select(o => new Uri(o)).ToList(); var pool = new StaticConnectionPool(lstUrls); var settings = new ConnectionSettings(pool); _elasticClient = new ElasticClient(settings); } return(_elasticClient); }
public void InitElasticSearchUsingPool() { //var uri = new Uri("http://*****:*****@"http://localhost:{port}")); var pool = new StaticConnectionPool(uris); var settings = new ConnectionSettings(pool); _elasticClient = new ElasticClient(settings); }
public void UsesRelativePathForPing() { var pool = new StaticConnectionPool(new[] { new Uri("http://localhost:9200/elasticsearch/") }); var connection = new HttpWebRequestConnectionTests.TestableHttpWebRequestConnection(); var settings = new ConnectionSettings(pool, connection); var client = new ElasticClient(settings); var healthResponse = client.Ping(); connection.LastRequest.Address.AbsolutePath.Should().StartWith("/elasticsearch/"); }
/// <summary> /// 通过连接池链接 /// </summary> public void ConnectionPoolLink() { var nodes = new Uri[] { new Uri("http://myserver1:9200"), new Uri("http://myserver2:9200"), new Uri("http://myserver3:9200") }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool); var client = new ElasticClient(settings); }
public ESearchService() { var nodes = new Uri[] { new Uri(mainPath) }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool).DisableDirectStreaming(); _client = new ElasticClient(settings); }
public GithubIssue2052() { var pool = new StaticConnectionPool(new List <Uri> { new Uri("http://localhost:9200") }); var memoryConnection = new InMemoryConnection(); var connectionSettings = new ConnectionConfiguration(pool, memoryConnection) .DisableDirectStreaming(); this._client = new ElasticLowLevelClient(connectionSettings); }
/** * ==== Custom indexing client * * Since Elasticsearch will automatically reroute ingest requests to ingest nodes, you don't have to specify or configure any routing * information. However, if you're doing heavy ingestion and have dedicated ingest nodes, it makes sense to send index requests to * these nodes directly, to avoid any extra hops in the cluster. * * The simplest way to achieve this is to create a dedicated "indexing" client instance, and use it for indexing requests. */ public void CustomClient() { var pool = new StaticConnectionPool(new [] //<1> list of ingest nodes { new Uri("http://ingestnode1:9200"), new Uri("http://ingestnode2:9200"), new Uri("http://ingestnode3:9200") }); var settings = new ConnectionSettings(pool); var indexingClient = new ElasticClient(settings); }
public void Usage() { var pool = new StaticConnectionPool(new[] { new Node(new Uri("http://localhost:9200")) }); var connection = new HttpConnection(); var serializer = LowLevelRequestResponseSerializer.Instance; var product = ElasticsearchProductRegistration.Default; var settings = new TransportConfiguration(pool, connection, serializer, product); var transport = new Transport <TransportConfiguration>(settings); var response = transport.Request <StringResponse>(HttpMethod.GET, "/"); }
public void UsesRelativePathForPing() { var pool = new StaticConnectionPool(new[] { new Uri("http://localhost:9200/elasticsearch/") }); var settings = new ConnectionSettings(pool, new HttpConnectionTests.TestableHttpConnection(response => { response.RequestMessage.RequestUri.AbsolutePath.Should().StartWith("/elasticsearch/"); })); var client = new ElasticClient(settings); var healthResponse = client.Ping(); }
public ElasticClient ElasticSearchClient() { var node = new Uri[] { new Uri("https://localhost:9200/"), }; var connectionPool = new StaticConnectionPool(node); var connectionSettings = new ConnectionSettings(connectionPool).DisableDirectStreaming(); var elesticClient = new ElasticClient(connectionSettings); return(elesticClient); }
private IElasticClient GetElasticClient() { var nodes = new List <Uri> { new Uri(elasticUrl) }; var connectionPool = new StaticConnectionPool(nodes); var connectionSettings = new ConnectionSettings(connectionPool); return(new ElasticClient(connectionSettings)); }
private IElasticClient CreatElasticClient() { var str = _elasticSearchConfigration.ConnectionString; var strs = str.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var nodes = strs.Select(s => new Uri(s)).ToList(); var connectionPool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(connectionPool) .BasicAuthentication(_elasticSearchConfigration.AuthUserName, _elasticSearchConfigration.AuthPassWord); return(new ElasticClient(settings)); }
protected override void InitializeTarget() { base.InitializeTarget(); var uri = GetConnectionString(ConnectionStringName) ?? Uri; var nodes = uri.Split(',').Select(url => new Uri(url)); var connectionPool = new StaticConnectionPool(nodes); var config = new ConnectionConfiguration(connectionPool); _client = new ElasticsearchClient(config, serializer:ElasticsearchSerializer); if (!String.IsNullOrEmpty(ExcludedProperties)) _excludedProperties = new List<string>(ExcludedProperties.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries)); }
protected override void InitializeTarget() { base.InitializeTarget(); ConnectionStringSettings connectionStringSettings = null; if (!string.IsNullOrEmpty(ConnectionStringName)) connectionStringSettings = ConfigurationManager.ConnectionStrings[ConnectionStringName]; var uri = connectionStringSettings == null ? Uri : connectionStringSettings.ConnectionString; var nodes = uri.Split(',').Select(url => new Uri(url)); var connectionPool = new StaticConnectionPool(nodes); var config = new ConnectionConfiguration(connectionPool); _client = new ElasticsearchClient(config, serializer:ElasticsearchSerializer); }
public void StaticConnectionPool_ThrowsAndDoesNotRetry_On_401_Async() { var nodes = new Uri[] { new Uri("http://*****:*****@localhost:9200"), new Uri("http://*****:*****@localhost:9201") }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool) .ThrowOnElasticsearchServerExceptions() .MaximumRetries(3); var client = new ElasticClient(settings); var e = Assert.Throws<ElasticsearchServerException>(async () => await client.RootNodeInfoAsync()); e.Status.Should().Be(401); }
public async void StaticConnectionPool_DoesNotThrowOrRetry_On_401_Async() { var nodes = new Uri[] { new Uri("http://*****:*****@localhost:9200"), new Uri("http://*****:*****@localhost:9201") }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool) .MaximumRetries(3); var client = new ElasticClient(settings); var r = await client.RootNodeInfoAsync(); r.IsValid.Should().BeFalse(); r.ConnectionStatus.HttpStatusCode.Should().Be(401); r.ConnectionStatus.Metrics.Requests.Count.Should().Be(1); r.ConnectionStatus.Metrics.Requests[0].RequestType.Should().Be(RequestType.Ping); r.ConnectionStatus.NumberOfRetries.Should().Be(0); }
/// <summary> /// Get the bulk connection pool of hosts /// </summary> /// <returns></returns> private ElasticClient getClient() { var nodes = new List<Uri>(); foreach (var host in _hosts) { var url = string.Format("http://{0}:{1}", host, _port); nodes.Add(new Uri(url)); } var pool = new StaticConnectionPool(nodes.ToArray()); var settings = new ConnectionSettings(pool) .ExposeRawResponse(); if (_disablePing) settings.DisablePing(); else if (_pingTimeout != 0) settings.SetPingTimeout(_pingTimeout); var client = new ElasticClient(settings); return client; }
public async void ConnectionPool_DoesNotThrowOnServerExceptions_ThrowsMaxRetryException_OnDeadNodes_Async() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9201), ElasticsearchConfiguration.CreateBaseUri(9202), ElasticsearchConfiguration.CreateBaseUri(9203), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .SetTimeout(1000) ); try { var result = await client.SearchAsync<ElasticsearchProject>(s => s.MatchAll()); result.IsValid.Should().BeFalse(); } catch (MaxRetryException) { Assert.Pass("MaxRetryException caught"); } catch (Exception e) { Assert.Fail("Did not expect exception of type {0} to be caught", e.GetType().Name); } }
public void ConnectionPool_DoesNotThrowOnServerExceptions_ThrowsMaxRetryException_OnDeadNodes() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9201), ElasticsearchConfiguration.CreateBaseUri(9202), ElasticsearchConfiguration.CreateBaseUri(9203), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .SetTimeout(1000) ); var e = Assert.Throws<MaxRetryException>(() => { var result = client.Search<ElasticsearchProject>(s => s.MatchAll()); result.IsValid.Should().BeFalse(); }); e.Should().NotBeNull(); }
public void ConnectionPool_ThrowOnServerExceptions_ThrowsElasticsearchServerException() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9200), ElasticsearchConfiguration.CreateBaseUri(9200), ElasticsearchConfiguration.CreateBaseUri(9200), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .ThrowOnElasticsearchServerExceptions() .SetTimeout(1000) ); var e = Assert.Throws<ElasticsearchServerException>(() => { var index = ElasticsearchConfiguration.NewUniqueIndexName(); var create = client.CreateIndex(index); var close = client.CloseIndex(index); var result = client.Search<ElasticsearchProject>(s => s.Index(index)); }); e.Should().NotBeNull(); }
public void ConnectionPool_SingleNode_PingExceptionThrowsMaxRetry_Async() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9201), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .SetTimeout(1000) ); var e = Assert.Throws<MaxRetryException>(async () => { var result = await client.SearchAsync<ElasticsearchProject>(s => s .MatchAll() ); result.IsValid.Should().BeFalse(); }); e.Should().NotBeNull(); }
public void Unauthorized_With_Ping_Disabled() { var nodes = new Uri[] { new Uri("http://*****:*****@localhost:9200"), new Uri("http://*****:*****@localhost:9201") }; var pool = new StaticConnectionPool(nodes); var settings = new ConnectionSettings(pool) .MaximumRetries(3) .DisablePing(); var client = new ElasticClient(settings); var r = client.RootNodeInfo(); r.IsValid.Should().BeFalse(); r.ConnectionStatus.HttpStatusCode.Should().Be(401); r.ConnectionStatus.Metrics.Requests.Count.Should().Be(1); r.ConnectionStatus.Metrics.Requests[0].RequestType.Should().Be(RequestType.ElasticsearchCall); r.ConnectionStatus.NumberOfRetries.Should().Be(0); }
public void ConnectionPool_SingleNode_PingExceptionThrowsMaxRetry() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9201), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .SetTimeout(1000) .MaximumRetries(1) ); var e = Assert.Throws<MaxRetryException>(() => client.Search<ElasticsearchProject>(s => s.MatchAll())); e.Should().NotBeNull(); Assert.Pass(e.ToString()); }
/// <summary> /// Get the bulk connection pool of hosts /// </summary> /// <returns></returns> private ElasticClient getClient() { var nodes = new List<Uri>(); foreach (var host in _hosts) { var uri = ComposeUri(host, _port, _ssl, _username, _password); nodes.Add(uri); } var pool = new StaticConnectionPool(nodes.ToArray()); var settings = new ConnectionSettings(pool) .ExposeRawResponse(); if (_disablePing) settings.DisablePing(); else if (_pingTimeout != 0) settings.SetPingTimeout(_pingTimeout); var client = new ElasticClient(settings); return client; }
public async void ConnectionPool_ThrowOnServerExceptions_ThrowsElasticsearchServerException_Async() { var uris = new [] { ElasticsearchConfiguration.CreateBaseUri(9200), ElasticsearchConfiguration.CreateBaseUri(9200), ElasticsearchConfiguration.CreateBaseUri(9200), }; var connectionPool = new StaticConnectionPool(uris); var client = new ElasticClient(new ConnectionSettings(connectionPool) .ThrowOnElasticsearchServerExceptions() .SetTimeout(1000) ); try { var index = ElasticsearchConfiguration.NewUniqueIndexName(); var create = await client.CreateIndexAsync(i=>i.Index(index)); var close = await client.CloseIndexAsync(i=>i.Index(index)); var result = await client.SearchAsync<ElasticsearchProject>(s => s.Index(index)); } catch (ElasticsearchServerException) { Assert.Pass("ElasticearchServerException caught"); } catch (Exception e) { Assert.Fail("Did not expect exception of type {0} to be caught", e.GetType().Name); } }