ASP.net 核心中如何在运行时更新 HttpClient 基址

How to update HttpClient base address at runtime in ASP.net core

我使用 ASP.net 核心创建了几个微服务 API
这些微服务之一 returns 其他微服务的确切地址
如果地址更改,如何在不重新启动的情况下更新任何这些微服务的地址

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);
    }
}

如果您要构建基于微服务的解决方案,迟早(更早)您会遇到一种服务需要与另一种服务通信的情况。为了做到这一点,调用者必须知道目标微服务在网络中的确切位置,它们在其中运行。

您必须以某种方式提供目标微服务侦听请求的 IP 地址端口。您可以使用配置文件或环境变量来实现,但这种方法有一些缺点和局限性。

  1. 首先,您必须维护并正确部署 所有环境的配置文件:本地开发, 测试、预生产和生产。忘记更新任何一个 添加新服务或移动现有服务时的这些配置 一个到不同的节点将导致在运行时发现错误。
  2. 其次,更重要的问题是它只能在static中工作 环境,意思是你不能动态地add/remove节点, 因此您将无法动态扩展您的系统。这 自主扩展和部署给定微服务的能力是其中之一 基于微服务架构的主要优势,我们做到了 不想失去这个能力。

因此我们需要引入服务发现。服务发现是一种允许服务找到彼此的网络位置的机制。这种模式有很多可能的实现方式。

我们有两种类型的服务发现:客户端和服务器端,您可以在 ASP.NET 个项目中找到一个好的 NuGet 包来处理。