GitHub地址:https://github.com/vipwan/Biwen.Microsoft.Extensions.ServiceDiscovery.Consul

使用方式

  1. 添加 NuGet 包
dotnet add package Biwen.Microsoft.Extensions.ServiceDiscovery.Consul -pre
  1. 配置好 Consul 的连接

在 Consul 中注册了名为 todo 的服务

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",
};
});
  1. 添加 Consule 服务发现的端点解析器
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
{ }

Microsoft.Extensions.ServiceDiscovery 的 Consul 实现的更多相关文章

  1. Microsoft.Extensions.Options支持什么样的配置类?

    在.Net core中,微软放弃了笨重基于XML的.Config配置文件(好吧,像我这种咸鱼早都忘了如何自己写一个Section了). 现在主推新的高度可扩展的配置文件(参见此处) 对于新的配置系统, ...

  2. asp.net core 2.0 Microsoft.Extensions.Logging 文本文件日志扩展

    asp.net core微软官方为日志提供了原生支持,有如下实现 Console Debug EventLog AzureAppServices TraceSource EventSource 并且在 ...

  3. DotNetCore跨平台~一起聊聊Microsoft.Extensions.DependencyInjection

    写这篇文章的心情:激动 Microsoft.Extensions.DependencyInjection在github上同样是开源的,它在dotnetcore里被广泛的使用,比起之前的autofac, ...

  4. Asp.Net Core 2.0 项目实战(9) 日志记录,基于Nlog或Microsoft.Extensions.Logging的实现及调用实例

    本文目录 1. Net下日志记录 2. NLog的使用     2.1 添加nuget引用NLog.Web.AspNetCore     2.2 配置文件设置     2.3 依赖配置及调用     ...

  5. Microsoft.Extensions.DependencyInjection不同版本导致EF出现内存泄露。

    我的代码里将IServiceProvider放入ServiceLocator中遇到的问题. 注:以下所有例子都是Console里的结论,AspNetCore里不管怎么玩都没有问题,有其他帖子测试出在A ...

  6. 检测到包降级: Microsoft.Extensions.Configuration.Abstractions 从 2.1.1 降 2.1.0

    解决方法:工具-nuget管理包-程序管理控制台-选择 项目- 执行 -Install-Package Microsoft.Extensions.Configuration.Abstractions ...

  7. 微软日志工厂 Microsoft.Extensions.Logging 中增加 log4net 的日志输出

    前提: 需要nuget   Microsoft.Extensions.Logging.Log4Net.AspNetCore   2.2.6: 描述:解决 .net core 微软日志工厂 Micros ...

  8. 解析 Microsoft.Extensions.DependencyInjection 2.x 版本实现

    项目使用了 Microsoft.Extensions.DependencyInjection 2.x 版本,遇到第2次请求时非常高的内存占用情况,于是作了调查,本文对 3.0 版本仍然适用. 先说结论 ...

  9. 使用诊断工具观察 Microsoft.Extensions.DependencyInjection 2.x 版本的内存占用

    目录 准备工作 大量接口与实现类的生成 elasticsearch+kibana+apm asp.net core 应用 请求与快照 Kibana 上的请求记录 请求耗时的分析 请求内存的分析 第2次 ...

  10. Microsoft.Extensions.DependencyInjection 之三:展开测试

    目录 前文回顾 IServiceCallSite CallSiteFactory ServiceProviderEngine CompiledServiceProviderEngine Dynamic ...

随机推荐

  1. foobar2000 v1.6.14 汉化版(2023.01.12更新)

    foobar2000 v1.6.14 汉化版 -----------------------[软件截图]---------------------- -----------------------[软 ...

  2. TEN Framework 入坑记

    TL;DR TEN Framework 最初叫 Astra,后改为 TEN,即 Transformative Extensions Network. 我第一次见到 TEN (那时还叫 Astra)是在 ...

  3. 现在 Llama 具备视觉能力并可以在你的设备上运行 - 欢迎使用 Llama 3.2

    Llama 3.2 来了!今天,我们欢迎 Llama 系列的下一个版本加入 Hugging Face.这次,我们很高兴与 Meta 合作发布多模态和小型模型.在 Hub 上提供了十个开源模型 (5 个 ...

  4. jmeter测试rpc接口-使用dubbo框架调用

    1.下载用于测试dubbo的spring boot项目 参考文章: http://t.zoukankan.com/111testing-p-11297038.html https://zhuanlan ...

  5. URL是什么

    URL是什么 URL(Uniform Resource Locator,统一资源定位器) URL的组成: 协议://{域名|主机名|IP}:端口/路径/文件名?参数#锚点 协议 Scheme/Prot ...

  6. costmap代价地图

    1 什么是costmap代价地图 在机器人进行路径规划时,我们需要明白规划算法是依靠什么在地图上来计算出来一条路径的.依靠的是gmapping扫描构建的一张环境全局地图,但是仅仅依靠一张原始的全局地图 ...

  7. WSGI、mini-web框架

    阅读目录: 1.服务器动态资源请求 2.应用程序示例 3.Web 动态服务器 4.mini-web框架-1-文件结构 5.mini-web框架-2-显示页面 6.mini-web框架-3-替换模板 一 ...

  8. C# 动态调用webservice代码

    /// <summary> /// 动态调用WebService /// </summary> /// <param name="url">UR ...

  9. Redhat7重置root管理员密码

    如果要重置Red Hat Enterprise Linux Server release 7.0 的root常见有2种办法(均测试有效) rd.break方法 1.重启Linux系统主机并出现引导界面 ...

  10. .NET 8.0 开源在线考试系统(支持移动端)

    前言 推荐一款基于.NET 8.0 免费开源跨平台在线考试系统,系统不仅支持桌面端,还特别优化了移动端的用户体验. 通过本系统可以轻松搭建自己的在线考试平台,实现随时随地的测试与评估. 本文将详细介绍 ...