Biwen.Microsoft.Extensions.ServiceDiscovery 1.0.0-pre1

This is a prerelease version of Biwen.Microsoft.Extensions.ServiceDiscovery.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Biwen.Microsoft.Extensions.ServiceDiscovery --version 1.0.0-pre1
NuGet\Install-Package Biwen.Microsoft.Extensions.ServiceDiscovery -Version 1.0.0-pre1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Biwen.Microsoft.Extensions.ServiceDiscovery" Version="1.0.0-pre1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Biwen.Microsoft.Extensions.ServiceDiscovery --version 1.0.0-pre1
#r "nuget: Biwen.Microsoft.Extensions.ServiceDiscovery, 1.0.0-pre1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Biwen.Microsoft.Extensions.ServiceDiscovery as a Cake Addin
#addin nuget:?package=Biwen.Microsoft.Extensions.ServiceDiscovery&version=1.0.0-pre1&prerelease

// Install Biwen.Microsoft.Extensions.ServiceDiscovery as a Cake Tool
#tool nuget:?package=Biwen.Microsoft.Extensions.ServiceDiscovery&version=1.0.0-pre1&prerelease

Microsoft.Extensions.ServiceDiscovery集成Consul

使用方式

1.安装Nuget包


dotnet add package Biwen.Microsoft.Extensions.ServiceDiscovery.Consul -pre

2 Enjoy

builder.Services.AddServiceDiscovery().AddConsulServiceEndPointResolver();


using Consul.AspNetCore;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.Extensions.ServiceDiscovery.Abstractions;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

//健康监测
builder.Services.AddHealthChecks().AddCheck("test", () =>
{
    return new Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult(
        Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy, "健康检测");
});

//注册 Consul服务和发现
builder.Services.AddConsul().AddConsulServiceRegistration(cfg =>
    {
        cfg.Meta = new Dictionary<string, string>() { { "Weight", "1" } };
        cfg.ID = "SVC1";
        cfg.Port = 5124;
        cfg.Name = "todo";
        cfg.Address = "http://127.0.0.1";
        cfg.Tags = ["MicroSvc"];
        cfg.Check = new Consul.AgentServiceCheck
        {
            DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(15),//服务启动多久后注册
            Interval = TimeSpan.FromSeconds(15),//健康检查时间间隔,或者称为心跳间隔
            HTTP = "http://127.0.0.1:5124/health",//健康检查地址
            Timeout = TimeSpan.FromSeconds(5),
            Method = "GET",
        };
    });


// 使用Microsoft.Extensions.ServiceDiscovery实现负载均衡 & Consul
builder.Services.AddServiceDiscovery().AddConsulServiceEndPointResolver();

// 默认是轮询算法,当前包含了
// RoundRobinServiceEndPointSelectorProvider轮询,
// RandomServiceEndPointSelectorProvider随即,
// PickFirstServiceEndPointSelectorProvider第一个.
// PowerOfTwoChoicesServiceEndPointSelectorProvider选择负载最轻的端点进行分布式负载均衡,当提供的任何一个端点不具备该功能时,降级为随机选择端点

builder.Services.ConfigureHttpClientDefaults(static http =>
{
    // 可以使用自己的算法 下面使用随机算法
    http.UseServiceDiscovery(RandomServiceEndPointSelectorProvider.Instance);
});

//使用IHttpClientFactory
builder.Services.AddHttpClient("todo", cfg =>
{
    cfg.BaseAddress = new("http://todo");
});

builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});

var app = builder.Build();

// Consul健康监测
app.UseHealthChecks("/health");

#region apis

var sampleTodos = new Todo[] {
    new(1, "Walk the dog"),
    new(2, "Do the dishes", DateOnly.FromDateTime(DateTime.Now)),
    new(3, "Do the laundry", DateOnly.FromDateTime(DateTime.Now.AddDays(1))),
    new(4, "Clean the bathroom"),
    new(5, "Clean the car", DateOnly.FromDateTime(DateTime.Now.AddDays(2)))
};

var todosApi = app.MapGroup("/todos");
todosApi.MapGet("/", () => sampleTodos);
todosApi.MapGet("/{id}", (int id) =>
    sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
        ? Results.Ok(todo)
        : Results.NotFound());

#endregion

#region 测试服务发现和负载

app.MapGet("/test", async (IHttpClientFactory clientFactory) =>
{
    var client = clientFactory.CreateClient("todo");
    var response = await client.GetAsync("/todos");
    var todos = await response.Content.ReadAsStringAsync();
    return Results.Content(todos, contentType: "application/json");
});

#endregion

app.Run();

public record Todo(int Id, string? Title, DateOnly? DueBy = null, bool IsComplete = false);

[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{

}


3 More

Microsoft.Extensions.ServiceDiscovery

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 36 5/22/2024
1.0.0-pre6 45 4/29/2024
1.0.0-pre5 54 4/11/2024
1.0.0-pre4 75 3/22/2024
1.0.0-pre1 82 1/19/2024

init