Microsoft.Extensions.ServiceDiscovery 的 Consul 实现
GitHub地址:https://github.com/vipwan/Biwen.Microsoft.Extensions.ServiceDiscovery.Consul
使用方式
- 添加 NuGet 包
dotnet add package Biwen.Microsoft.Extensions.ServiceDiscovery.Consul -pre
- 配置好 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",
};
});
- 添加 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 实现的更多相关文章
- Microsoft.Extensions.Options支持什么样的配置类?
在.Net core中,微软放弃了笨重基于XML的.Config配置文件(好吧,像我这种咸鱼早都忘了如何自己写一个Section了). 现在主推新的高度可扩展的配置文件(参见此处) 对于新的配置系统, ...
- asp.net core 2.0 Microsoft.Extensions.Logging 文本文件日志扩展
asp.net core微软官方为日志提供了原生支持,有如下实现 Console Debug EventLog AzureAppServices TraceSource EventSource 并且在 ...
- DotNetCore跨平台~一起聊聊Microsoft.Extensions.DependencyInjection
写这篇文章的心情:激动 Microsoft.Extensions.DependencyInjection在github上同样是开源的,它在dotnetcore里被广泛的使用,比起之前的autofac, ...
- Asp.Net Core 2.0 项目实战(9) 日志记录,基于Nlog或Microsoft.Extensions.Logging的实现及调用实例
本文目录 1. Net下日志记录 2. NLog的使用 2.1 添加nuget引用NLog.Web.AspNetCore 2.2 配置文件设置 2.3 依赖配置及调用 ...
- Microsoft.Extensions.DependencyInjection不同版本导致EF出现内存泄露。
我的代码里将IServiceProvider放入ServiceLocator中遇到的问题. 注:以下所有例子都是Console里的结论,AspNetCore里不管怎么玩都没有问题,有其他帖子测试出在A ...
- 检测到包降级: Microsoft.Extensions.Configuration.Abstractions 从 2.1.1 降 2.1.0
解决方法:工具-nuget管理包-程序管理控制台-选择 项目- 执行 -Install-Package Microsoft.Extensions.Configuration.Abstractions ...
- 微软日志工厂 Microsoft.Extensions.Logging 中增加 log4net 的日志输出
前提: 需要nuget Microsoft.Extensions.Logging.Log4Net.AspNetCore 2.2.6: 描述:解决 .net core 微软日志工厂 Micros ...
- 解析 Microsoft.Extensions.DependencyInjection 2.x 版本实现
项目使用了 Microsoft.Extensions.DependencyInjection 2.x 版本,遇到第2次请求时非常高的内存占用情况,于是作了调查,本文对 3.0 版本仍然适用. 先说结论 ...
- 使用诊断工具观察 Microsoft.Extensions.DependencyInjection 2.x 版本的内存占用
目录 准备工作 大量接口与实现类的生成 elasticsearch+kibana+apm asp.net core 应用 请求与快照 Kibana 上的请求记录 请求耗时的分析 请求内存的分析 第2次 ...
- Microsoft.Extensions.DependencyInjection 之三:展开测试
目录 前文回顾 IServiceCallSite CallSiteFactory ServiceProviderEngine CompiledServiceProviderEngine Dynamic ...
随机推荐
- 在Windows平台使用源码编译和安装PyTorch3D指定版本
最近在部署 SyncTalk 虚拟数字人项目时,需要安装很多依赖项,在执行到pip install --no-index --no-cache-dir pytorch3d -f https://dl. ...
- 树莓派2 CentOS7.9 安装配置笔记
1. 镜像下载与安装 http://isoredirect.centos.org/altarch/7/isos/armhfp/找到https://mirrors.tuna.tsinghua.edu.c ...
- 2021年8月国产数据库排行榜:TiDB稳榜首,达梦返前三,Kingbase进十强,各厂商加速布局云生态
8月份的国产数据库流行度排行榜新鲜出炉.本月共有139个数据库参与了排名. 先来看看排行榜前五名.PingCAP的TiDB分数连续第二个月上涨,总分达到630.21,以136.48的分数差拉开了与第二 ...
- 封装setItem 和 getItem 本地存储
store.js 文件 按需导出setItem 和 getItem 函数 :在utils文件里面 : export const setItem = (key, value) => { // 复杂 ...
- 云原生爱好者周刊:GitHub 官方文档终于开源了!
云原生一周动态要闻: API 在 Kubernetes 1.22 中被删除 ContainIQ 公开发布 - Kubernetes 本地实时监控! Sophos 收购 Capsule8 开源项目推荐 ...
- 云原生爱好者周刊:Grafana Loki 免费电子书
云原生一周动态要闻: Apache Log4j 2.17.1 修复远程代码执行漏洞 CNCF 发布 2021 年度报告 极狐(GitLab)发布业内首款"GitNative" De ...
- OpenFunction 0.7.0 发布: OpenFunction Gateway、多语言及 Helm 安装支持
OpenFunction 是一个开源的云原生 FaaS(Function as a Service,函数即服务)平台,旨在帮助开发者专注于业务逻辑的研发.在过去的几个月里,OpenFunction 社 ...
- C++新版本特性
C++新特性 1.C++11 中的新特性 C++11 引入了许多新特性,包括自动类型推导.lambda 表达式.右值引用等.下面介绍其中的一些重要特性. 1.1 自动类型推导(Type Inferen ...
- 霍夫(Hough)直线变换(直线检测)
0 原理 霍夫变换在检测各种形状的的技术中非常流行,如果你要检测的形状可以用数学表达式写出,你就可以是使用霍夫变换检测它.及时要检测的形状存在一点破坏或者扭曲也可以使用.我们下面就看看如何使用霍夫变换 ...
- 搞清楚这个老六的真面目!逐层‘剥开’人工智能中的卷积神经网络(CNN)
第三章:超越基础--图像中的特征检测 上一篇<揭开计算机视觉的神秘面纱,原来机器是这样"看图"的!> 本篇序言:上一篇我们实现并训练了一个神经网络,成功让计算机&quo ...