Last active
June 28, 2020 21:51
-
-
Save GeradeDev/53f61c56676e0f9de414927c0eb2b615 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConsulHttpClient : IConsulHttpClient | |
{ | |
private readonly HttpClient _client; | |
private IConsulClient _consulclient; | |
public ConsulHttpClient(HttpClient client, IConsulClient consulclient) | |
{ | |
_client = client; | |
_consulclient = consulclient; | |
} | |
public async Task<T> GetAsync<T>(string serviceName, Uri requestUri) | |
{ | |
var uri = await GetRequestUriAsync(serviceName, requestUri); | |
var response = await _client.GetAsync(uri); | |
if (!response.IsSuccessStatusCode) | |
{ | |
return default(T); | |
} | |
var content = await response.Content.ReadAsStringAsync(); | |
return JsonConvert.DeserializeObject<T>(content); | |
} | |
private async Task<Uri> GetRequestUriAsync(string serviceName, Uri uri) | |
{ | |
//Get all services registered on Consul | |
var allRegisteredServices = await _consulclient.Agent.Services(); | |
//Get all instance of the service went to send a request to | |
var registeredServices = allRegisteredServices.Response?.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).Select(x => x.Value).ToList(); | |
//Get a random instance of the service | |
var service = GetRandomInstance(registeredServices, serviceName); | |
if (service == null) | |
{ | |
throw new ConsulServiceNotFoundException($"Consul service: '{serviceName}' was not found.", | |
serviceName); | |
} | |
var uriBuilder = new UriBuilder(uri) | |
{ | |
Host = service.Address, | |
Port = service.Port | |
}; | |
return uriBuilder.Uri; | |
} | |
private AgentService GetRandomInstance(IList<AgentService> services, string serviceName) | |
{ | |
Random _random = new Random(); | |
AgentService servToUse = null; | |
servToUse = services[_random.Next(0, services.Count)]; | |
return servToUse; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment