趁着刚过完年,还没有开始做业务的时候,学习下consul 概念自己去官网看,这里只讲下具体实现

官网下载https://www.consul.io/downloads 我下载的是Windows版本

启动consul命令

consul agent -dev -client 0.0.0.0

新建.net5的api项目,.net5直接默认是swagger

4.新建扩展服务注册到Consul方法,ConsulExtenions.cs

 public static void ConsulRegist(this IConfiguration configuration)
{
try
{
string ip = configuration["ip"];
string port = configuration["port"];
string weight = configuration["weight"];
string consulAddress = configuration["ConsulAddress"];
string consulCenter = configuration["ConsulCenter"]; ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri(consulAddress);
c.Datacenter = consulCenter;
}); client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = "CommService" + Guid.NewGuid(),//--唯一的
Name = "CommService",//分组---根据Service
Address = ip,
Port = int.Parse(port),
Tags = new string[] { weight.ToString() },//额外标签信息
Check = new AgentServiceCheck()
{
Interval = TimeSpan.FromSeconds(12),
HTTP = $"http://{ip}:{port}/Api/Health/Index", // 给到200
Timeout = TimeSpan.FromSeconds(5),
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)
}//配置心跳
});
Console.WriteLine($"{ip}:{port}--weight:{weight}"); //命令行参数获取
}
catch (Exception ex)
{
Console.WriteLine($"Consul注册:{ex.Message}");
}
}

ip port 配置在appsettings.json里面

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ip": "localhost",
"port": 5000,
"weight": 1,
"ConsulAddress": "http://127.0.0.1:8500",
"ConsulCenter": "dc1"
}

Startup注册ConsulRegist方法

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//if (env.IsDevelopment())
//{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "comm.api v1"));
//} // app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Consul注册
this.Configuration.ConsulRegist();
}

可以用dotnet 启动2个comm.api.dll  端口号自己随便取,我取的5000和6000 HealthController为配置的心跳api返回的结果

再来看下Consul 会发现多了CommService

2 Instances为端口号5000和6000的api

注册完成了,接下来实现调用看效果图

调用代码

 public static AgentService ChooseService(string serviceName)
{
using (ConsulClient client = new ConsulClient(c => c.Address = new Uri("http://localhost:8500")))
{
var services = client.Agent.Services().Result.Response;
// 找出目标服务
var targetServices = services.Where(c => c.Value.Service.Equals(serviceName)).Select(s => s.Value);
// 实现随机负载均衡
var targetService = targetServices.ElementAt(new Random().Next(1, 1000) % targetServices.Count());
Console.WriteLine($"{DateTime.Now} 当前调用服务为:{targetService.Address}:{targetService.Port}"); return targetService;
}
}
  public string GetCommUrl()
{
AgentService agentService = ConsulClientExtenions.ChooseService("CommService");
string url = $"http://{agentService.Address}:{agentService.Port}/api/Comm/GetProvince";
return url;
}

需要demo的留言

微服务学习.net5+consul的更多相关文章

  1. 微服务学习笔记(2)——使用Consul 实现 MagicOnion(GRpc) 服务注册和发现

    原文:微服务学习笔记(2)--使用Consul 实现 MagicOnion(GRpc) 服务注册和发现 1.下载打开Consul 笔者是windows下面开发的(也可以使用Docker). 官网下载w ...

  2. .NET Core微服务之基于Consul实现服务治理

    Tip: 此篇已加入.NET Core微服务基础系列文章索引 一.Consul基础介绍 Consul是HashiCorp公司推出的开源工具,用于实现分布式系统的服务发现与配置.与其他分布式服务注册与发 ...

  3. 微服务学习笔记(1)——使用MagicOnion实现gRPC

    原文:微服务学习笔记(1)--使用MagicOnion实现gRPC 1.什么是gRPC 官方文档:https://grpc.io/docs/guides/index.html 2.什么是MagicOn ...

  4. .NET Core 微服务学习与实践系列文章目录索引(2019版)

    参考网址: https://archy.blog.csdn.net/article/details/103659692 2018年,我开始学习和实践.NET Core,并开始了微服务的学习,以及通过各 ...

  5. SpringCloud微服务学习笔记

    SpringCloud微服务学习笔记 项目地址: https://github.com/taoweidong/Micro-service-learning 单体架构(Monolithic架构) Mon ...

  6. .NET Core微服务一:Consul服务中心

    本文的项目代码,在文章结尾处可以下载. 防爬虫,本文的网址是:https://www.cnblogs.com/shousiji/p/12253295.html 本文使用的环境:Windows10 64 ...

  7. Spring Cloud微服务学习笔记

    Spring Cloud微服务学习笔记 SOA->Dubbo 微服务架构->Spring Cloud提供了一个一站式的微服务解决方案 第一部分 微服务架构 1 互联网应用架构发展 那些迫使 ...

  8. .NET Core微服务之基于Consul实现服务治理(续)

    Tip: 此篇已加入.NET Core微服务基础系列文章索引 上一篇发布之后,很多人点赞和评论,不胜惶恐,这一篇把上一篇没有弄到的东西补一下,也算是给各位前来询问的朋友的一些回复吧. 一.Consul ...

  9. 最全的.NET Core跨平台微服务学习资源

    一.Asp.net Core基础 微软中文官网:https://docs.microsoft.com/zh-cn/aspnet/core/getting-started/ 微软英文官网:https:/ ...

随机推荐

  1. docker(mysql-redmine)

    一.安装docker 首先查看自己的版本,我的是centos 版本为 [root@localhost redmine]# uname -r 3.10.0-862.el7.x86_64 移除旧版本 yu ...

  2. C/C++ New与Delete (小例子)

    转自:http://blog.csdn.net/chenzujie/article/details/7011639   先来看两段小程序: 1). #include <iostream.h> ...

  3. C++类基本--随笔一

    #include <iostream> using namespace std; class Teacher { public: Teacher(int m=3,int n=2) { a= ...

  4. 31-1.解决service iptables save出错

    CentOS 7.x开始,CentOS开始使用systemd服务来代替daemon,原来管理系统启动和管理系统服务的相关命令全部由systemctl命令来代替.service命令只保留下了极少部分使用 ...

  5. Java 复习整理day07

    package com.it.demo05_innerclass; /* 案例: 演示内部类入门. 概述: 所谓的内部类指的是类里边还有一个类, 里边那个类叫: 内部类, 外边那个类, 叫外部类. 分 ...

  6. 设计模式(七)——适配器模式(SpringMVC框架分析)

    适配器模式 1 现实生活中的适配器例子 泰国插座用的是两孔的(欧标),可以买个多功能转换插头 (适配器) ,这样就可以使用了. 2 基本介绍 1) 适配器模式(Adapter Pattern)将某个类 ...

  7. shell编程基础一

    1.定义变量 a=1 shell定义变量要注意等号前后不能有空格,不然会报错,请严格按照格式编写. 2.打印输出 echo 1 使用echo打印,后面留一个空格. 3.shell中通过 ${变量名} ...

  8. Codeforces Round #682 (Div. 2) B. Valerii Against Everyone (思维)

    题意:给你一组数\(b\),对于每个\(b_i\),相对应的\(a_i=2^{b_i}\),问你是否能找出两个不相交的区间,使得两个区间的\(a_i\)的元素和相等. 题解:对于任意一个\(2^k\) ...

  9. __getattr__,__getattribute__和__get__的区别

    dir(object)  列出对象的大多数属性 getattr(object, name) 从object对象中获取name字符串指定的属性 hasattr(object, name) 如果objec ...

  10. Dapr微服务应用开发系列2:Hello World与SDK初接触

    题记:上篇介绍了Dapr的环境配置,这次我们来动手尝试一下Dapr应用的开发 Hello World Dapr应用的Hello World其实和其他的Hello World一样简单: 首先用你喜欢的语 ...