微服務(入門二):netcore經過consul註冊服務

 

基礎準備html


1.建立asp.net core Web 應用程序選擇Apijson

2.appsettings.json 配置consul服務器地址,以及本機ip和端口號信息api

 

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "Consul": {
    "IP": "127.0.0.1",
    "Port": "8500"

  },
  "Service": {
    "Name": "zyz"
  },
  "ip": "localhost",
  "port": "6655",

  "AllowedHosts": "*"
}

 

 

3.程序入口(program.cs)配置useurls,ip和port從配置文件(或者命令行中)讀取(命令行啓動方式:dotnet ConsulServer.dll --ip localhost --port 8644服務器

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace ConsulServer
{
    public class Program
    {

        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder().AddCommandLine(args)
              .Build();//獲取配置信息
            return WebHost.CreateDefaultBuilder(args)
                .UseUrls($"http://{ config["ip"]}:{config["port"]}")//配置ip地址和端口地址
                .UseStartup<Startup>();
        }

    }
}

 

 

4.配置基礎數據,而且調用註冊consul接口app

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using ConsulServer.ConsulApi;
using ConsulServer.entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace ConsulServer
{
    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 lifetime)
        {

        
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            ////配置信息單例
            //ConfigSingleton.setConfigSingleton(Configuration);
           
            app.UseMvc();

            ConsulEntity consulEntity = new ConsulEntity
            {
                ip = Configuration["ip"],
                port = int.Parse(Configuration["port"] ),
                ServiceName = "zyz",
                ConsulIP = Configuration["Consul:IP"],
                ConsulPort = Convert.ToInt32(Configuration["Consul:Port"])
            };
            app.RegisterConsul(lifetime, consulEntity);
        }

    }
}

 

 

 

 5.配置註冊信息asp.net

using Consul;
using ConsulServer.entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsulServer.ConsulApi
{
    /// <summary>
    /// consul
    /// </summary>
    public static class AppBuilderExtensions
    {

        /// <summary>
        /// 註冊consul
        /// </summary>
        /// <param name="app"></param>
        /// <param name="lifetime"></param>
        /// <param name="serviceEntity"></param>
        /// <returns></returns>
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ConsulEntity serviceEntity)
        {
            //consul地址
            Action<ConsulClientConfiguration> configClient = (consulConfig) =>
            {
                consulConfig.Address = new Uri($"http://{serviceEntity.ConsulIP}:{ serviceEntity.ConsulPort}");
                consulConfig.Datacenter = "dc1";
            };
            //創建鏈接
            var consulClient = new ConsulClient(configClient);
            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服務啓動多久後註冊
                Interval = TimeSpan.FromSeconds(10),//健康監測
                HTTP = string.Format($"http://{serviceEntity.ip}:{serviceEntity.port}/api/health"),//心跳檢測地址
                Timeout = TimeSpan.FromSeconds(5)
            };
            //註冊
            var registrtion = new AgentServiceRegistration()
            {

                Checks = new[] { httpCheck },
                ID = "zyzService" + Guid.NewGuid().ToString(),//服務編號不可重複
                Name = serviceEntity.ServiceName,//服務名稱
                Address = serviceEntity.ip,//ip地址
                Port = serviceEntity.port//端口

            };
            //註冊服務
            consulClient.Agent.ServiceRegister(registrtion);

            return app;
        }

    }
}

6.以命令行啓動程序查看consul(dotnet ConsulServer.dll --ip localhost --port 8644ide

 

 

 

快速入口:微服務(入門一):netcore安裝部署consul微服務

快速入口: 微服務(入門二):netcore經過consul註冊服務ui

快速入口: 微服務(入門三):netcore ocelot api網關結合consul服務發現this

快速入口:微服務(入門四):identityServer的簡單使用(客戶端受權) 

相關文章
相關標籤/搜索