Net Core微服务:Consul简介?将服务注册到 Consul中?服务消费者1?

一、Consul简介

1、Consul作用

      保存 服务的名称,IP,端口。

2、下载地址 https://www.consul.io/

       cmd运行:consul.exe agent -dev

      监测页面:http://127.0.0.1:8500/

 

 

二、Consul注册

1、net core 中将服务注册到 Consul中

(1)、vs安装Consul

  命令:install-package Consul

Net Core微服务:Consul简介?将服务注册到 Consul中?服务消费者1?_第1张图片

推荐:VS2019 Nuget找不到包的问题处理

(2)、获取服务地址,端口,名称,ID

(3)、将服务注册到Consul中,健康检查

(4)、服务退出

(5)、代码如下:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();


            #region  服务地址,端口,名称,ID
            string ip = Configuration["ip"]; //服务的ip
            string port = Configuration["port"];
            string serviceName = "MsgService";//服务的名字
            string serviceId = serviceName + Guid.NewGuid();//服务ID,全球唯一
            #endregion

            #region  将服务注册到Consul中,健康检查
            using (var consulClient = new ConsulClient(consulConfig))
            //using (var consulClient = new ConsulClient(c=> { c.Address = new Uri("http://127.0.0.1:8500");c.Datacenter = "dc1"; }))//注册
            {
                AgentServiceRegistration asr = new AgentServiceRegistration();
                asr.Address = ip;
                asr.Port = Convert.ToInt32(port);
                asr.Name = serviceName;
                asr.ID = serviceId;
                asr.Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                    HTTP = $"http://{ip}:{port}/api/Health",//健康检查地址
                    Interval = TimeSpan.FromSeconds(10),//每10秒检查,健康检查
                    Timeout = TimeSpan.FromSeconds(5) //超时时间

                };
                consulClient.Agent.ServiceRegister(asr).Wait();//异步,等待执行完毕
            }
            #endregion

            #region  服务退出
            appLifetime.ApplicationStopped.Register(() => {
                using (var consulClient = new ConsulClient(consulConfig))
                {
                    Console.WriteLine("应用退出,开始从consul注销");
                    consulClient.Agent.ServiceDeregister(serviceId).Wait();
                }
            });
            #endregion

        }
        /// 
        /// consul配置
        /// 
        /// 
        private void consulConfig(ConsulClientConfiguration c)
        {
            c.Address = new Uri("http://127.0.0.1:8500");//consul的地址
            c.Datacenter = "dc1";
        }

    }

(6)、启动服务,将服务地址,端口,添加到consul中

cmd中执行: dotnet msgservice.dll --ip 127.0.0.1 --port 6001

(7)、浏览器地址中http://127.0.0.1:8500/,查询服务启动信息,可添加多个服务。

 

三、服务消费者

using Consul;
using System;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace 服务消费者1
{
    class Program
    {
        static void Main(string[] args)
        {
            //连接consul
            using (var consul=new ConsulClient(c=> {c.Address = new Uri("http://127.0.0.1:8500");}))
            {
                /*
               var services = consul.Agent.Services().Result.Response;//获取consul注册的所有服务
               foreach(var s in services.Values)
               {
                   Console.WriteLine($"id={s.ID},service={s.Service},address={s.Address},port={s.Port}");
               }
               */


                #region 客户端负载均衡
                
                    //获得MsgService下所有服务
                    var services = consul.Agent.Services().Result.Response.Values.Where(item=>item.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase));
                    if(!services.Any())
                    {
                       Console.WriteLine("找不到服务器实例");
                    }
                    else
                    {
                        Random rand = new Random();
                        int index = rand.Next(services.Count());
                        var s = services.ElementAt(index);
                        //var s = services.ElementAt(Environment.TickCount%services.Count());
                        Console.WriteLine($"index={index},id={s.ID},service={s.Service},address={s.Address},port={s.Port}");

                        using (HttpClient http = new HttpClient())
                        using (var httpContent=new StringContent("{phoneNum:'119',msg:'help'}",Encoding.UTF8,"application/json"))
                        {
                           var r=http.PostAsync($"http://{s.Address}:{s.Port}/api/SMS/Send_HW", httpContent).Result;
                           Console.WriteLine(r.StatusCode);
                        }
                    }


                #endregion

            }
            Console.ReadKey();
        }
    }
}

 

你可能感兴趣的:(Net,Core)