2.24Service Discovery (ServiceDiscovery)
Service discovery is a mechanism that allows developers to reference external services using logical names rather than physical addresses (such as IP addresses and ports). For example, we can use furion instead of https://furion.net. The benefit of this approach is that service addresses can be modified through configuration at runtime without changing program code, while also enabling automatic selection of service endpoints to achieve load balancing. Service discovery is especially common in microservice architectures.
To use service discovery in HTTP remote requests, follow the steps below to configure it:
1. Install the Microsoft.Extensions.ServiceDiscovery Package
dotnet add package Microsoft.Extensions.ServiceDiscovery2. Configure and Enable the ServiceDiscovery Service
Register and configure the ServiceDiscovery service in the Startup.cs or Program.cs file:
services.AddServiceDiscovery();services.AddHttpRemote() .ConfigureHttpClientDefaults(clientBuilder => { clientBuilder.AddServiceDiscovery(); });3. Add Service Endpoints in the Configuration File
Configure the service endpoints in the appsettings.json file. The following example configures two services, furion and weixin, each containing multiple endpoints. Each time a request is sent, the system automatically selects an endpoint.
{ "Services": { "furion": { "https": ["localhost:5001", "furion.net"] }, "weixin": { "https": ["localhost:8080", "weixin.qq.com"] } }}4. Configure the BaseAddress of the HttpClient Client
Next, configure the BaseAddress of the HttpClient client so that logical names are used instead of concrete physical addresses when making requests.
// Configure the default clientservices.AddHttpClient(string.Empty, client =>{ client.BaseAddress = new Uri("https://furion");});// Configure a specific client, e.g. "weixin"services.AddHttpClient("weixin", client =>{ client.BaseAddress = new Uri("https://weixin");});5. Send the HTTP Remote Request
Finally, use the configured HttpClient to send the remote request:
// Send a request with the default clientawait httpRemoteService.GetAsStringAsync("docs"); // The request URL is: https://localhost:5001/docs or https://furion.net/docs// Send a request with the "weixin" clientawait httpRemoteService.GetAsStringAsync("userinfo", builder => builder.SetHttpClientName("weixin")); // The request URL is: https://localhost:8080/userinfo or https://weixin.qq.com/userinfoWith the steps above, you can easily implement service discovery functionality in a .NET application, simplifying service invocation and improving the flexibility and scalability of the system. To learn more about service discovery in .NET, see the Microsoft official documentation.