Поделиться через


.NET .NET Aspire service discovery

Из этой статьи вы узнаете, как работает обнаружение служб в проекте .NET.NET Aspire. .NET .NET Aspire включает функции для настройки обнаружения служб во время разработки и тестирования. Service discovery functionality works by providing configuration in the format expected by the configuration-based endpoint resolver from the .NET.NET Aspire AppHost project to the individual service projects added to the application model. For more information, see Service discovery in .NET.

Implicit service discovery by reference

Конфигурация обнаружения служб добавляется только для служб, на которые ссылается данный проект. Например, рассмотрим следующую программу AppHost:

var builder = DistributedApplication.CreateBuilder(args);

var catalog = builder.AddProject<Projects.CatalogService>("catalog");
var basket = builder.AddProject<Projects.BasketService>("basket");

var frontend = builder.AddProject<Projects.MyFrontend>("frontend")
                      .WithReference(basket)
                      .WithReference(catalog);

In the preceding example, the frontend project references the catalog project and the basket project. The two WithReference calls instruct the .NET.NET Aspire project to pass service discovery information for the referenced projects (catalog, and basket) into the frontend project.

Именованные конечные точки

Некоторые службы предоставляют несколько именованных конечных точек. Named endpoints can be resolved by specifying the endpoint name in the host portion of the HTTP request URI, following the format scheme://_endpointName.serviceName. Например, если служба с именем "корзина" предоставляет конечную точку с именем "панель мониторинга", URI https+http://_dashboard.basket можно использовать для указания этой конечной точки, например:

builder.Services.AddHttpClient<BasketServiceClient>(
    static client => client.BaseAddress = new("https+http://basket"));

builder.Services.AddHttpClient<BasketServiceDashboardClient>(
    static client => client.BaseAddress = new("https+http://_dashboard.basket"));

В предыдущем примере добавляются два класса HttpClient, один для основной службы корзины и один для панели мониторинга службы корзины.

Named endpoints using configuration

With the configuration-based endpoint resolver, named endpoints can be specified in configuration by prefixing the endpoint value with _endpointName., where endpointName is the endpoint name. Например, рассмотрим эту appsettings.json конфигурацию, определяющую конечную точку по умолчанию (без имени) и конечную точку с именем "панель мониторинга":

{
  "Services": {
    "basket": {
      "https": "https://10.2.3.4:8080", /* the https endpoint, requested via https://basket */
      "dashboard": "https://10.2.3.4:9999" /* the "dashboard" endpoint, requested via https://_dashboard.basket */
    }
  }
}

In the preceding JSON:

  • Конечная точка по умолчанию при разрешении https://basket является 10.2.3.4:8080.
  • The "dashboard" endpoint, resolved via https://_dashboard.basket is 10.2.3.4:9999.

Named endpoints in .NET.NET Aspire

var basket = builder.AddProject<Projects.BasketService>("basket")
    .WithHttpsEndpoint(hostPort: 9999, name: "dashboard");

Named endpoints in Kubernetes using DNS SRV

When deploying to Kubernetes, the DNS SRV service endpoint resolver can be used to resolve named endpoints. Например, следующее определение ресурса приведет к созданию записи DNS SRV для конечной точки с именем "default" и конечной точки с именем "dashboard", обе в сервисе с именем "корзина".

apiVersion: v1
kind: Service
metadata:
  name: basket
spec:
  selector:
    name: basket-service
  clusterIP: None
  ports:
  - name: default
    port: 8080
  - name: dashboard
    port: 9999

To configure a service to resolve the "dashboard" endpoint on the "basket" service, add the DNS SRV service endpoint resolver to the host builder as follows:

builder.Services.AddServiceDiscoveryCore();
builder.Services.AddDnsSrvServiceEndpointProvider();

Дополнительные сведения см. в AddServiceDiscoveryCore и AddDnsSrvServiceEndpointProvider.

Специальное имя порта "default" используется для указания конечной точки по умолчанию, определяемой с использованием URI https://basket.

Как и в предыдущем примере, добавьте функцию поиска служб в HttpClient для сервиса корзины.

builder.Services.AddHttpClient<BasketServiceClient>(
    static client => client.BaseAddress = new("https://basket"));

Аналогичным образом конечная точка панели мониторинга может быть нацелена следующим образом:

builder.Services.AddHttpClient<BasketServiceDashboardClient>(
    static client => client.BaseAddress = new("https://_dashboard.basket"));

См. также