protected override async Task ResolveAsync(CancellationToken cancellationToken) { var address = _address.Host.Replace("consul://", string.Empty); var _consulServiceProvider = new DiscoverProviderBuilder(_client).WithServiceName(address).WithCacheSeconds(5).Build(); var results = await _consulServiceProvider.GetAllHealthServicesAsync(); var balancerAddresses = new List <BalancerAddress>(); results.ForEach(result => { var addressArray = result.Split(":"); var host = addressArray[0]; var port = int.Parse(addressArray[1]) + 1; balancerAddresses.Add(new BalancerAddress(host, port)); }); // Pass the results back to the channel. Listener(ResolverResult.ForResult(balancerAddresses)); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var currentUri = request.RequestUri; if (currentUri is null) { throw new NullReferenceException(nameof(request.RequestUri)); } var discoverProvider = new DiscoverProviderBuilder(_consulClient) .WithCacheSeconds(5) .WithServiceName(currentUri.Host) .WithLoadBalancer(TypeLoadBalancer.RandomLoad) .WithLogger(_logger) .Build() ; var baseUri = await discoverProvider.GetSingleHealthServiceAsync(); if (baseUri.IsNullOrWhiteSpace()) { throw new NullReferenceException($"{currentUri.Host} does not contain helath service address!"); } else { var realRequestUri = new Uri($"{currentUri.Scheme}://{baseUri}{currentUri.PathAndQuery}"); request.RequestUri = realRequestUri; _logger.LogDebug($"RequestUri:{request.RequestUri}"); } try { return(await base.SendAsync(request, cancellationToken).ConfigureAwait(false)); } catch (Exception ex) { _logger?.LogDebug(ex, "Exception during SendAsync()"); throw; } finally { request.RequestUri = currentUri; } }