【发布时间】:2021-08-08 09:55:08
【问题描述】:
我使用 ASP.net 核心 API 创建了几个微服务
这些微服务之一返回其他微服务的确切地址
如果地址更改,如何在不重新启动的情况下更新这些微服务的地址
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("MainMicroservice", x =>
{
x.BaseAddress = new Uri("http://mainmicroservice.com");
});
services.AddHttpClient("Microservice1", x =>
{
x.BaseAddress = new Uri("http://microservice1.com");
});
services.AddHttpClient("Microservice2", x =>
{
x.BaseAddress = new Uri("http://microservice2.com");
});
services.AddHttpClient("Microservice3", x =>
{
x.BaseAddress = new Uri("http://microservice3.com");
});
}
}
public class Test
{
private readonly IHttpClientFactory _client;
public Test(IHttpClientFactory client)
{
_client = client;
}
public async Task<string> Test()
{
var repeat = false;
do
{
try
{
return await _client
.CreateClient("Microservice1")
.GetStringAsync("Test")
.ConfigureAwait(false);
}
catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.NotFound)
{
var newAddress = await _client
.CreateClient("MainMicroservice")
.GetStringAsync("Microservice1")
.ConfigureAwait(false);
//todo change address of microservice1
repeat = true;
}
} while (repeat);
}
}
【问题讨论】:
-
不分配基地址,给出调用GET、POST、PUT时的地址
-
性能方面有问题吗?
-
听起来第一个服务真的是一个配置源。您可以将其添加为 custom configuration provider 并使用它在您的 HttpClient 注册中提供的 URL。
-
OTOH 你问的是 DNS 的作用。如果您可以控制您的 DNS 域,则可以使用 ALIAS 记录创建重定向到特定服务器的知名服务名称。这样,将流量定向到不同服务器所需的只是更改 ALIAS
-
@Mehdi 不,不包括性能问题,但请确保您只有 1 个 httpclient 实例。如果您创建多个实例,则会导致性能影响
标签: c# asp.net-core microservices httpclient