ocelot集成consul服務發現

  • 首先下載consul 點擊這裏下載
  • 轉到解壓文件夾目錄輸入cmd命令  consul agent -dev (有時候會卡住按一下方向鍵上)
  • 在瀏覽器中輸入http://localhost:8500/ui 查看是否安裝成功成功以下圖所示

     

  • 在網站啓動的時候註冊服務,網站中止的時候卸載服務。
  • 服務的註冊
    • 先引用consul nuget包
    • 添加配置文件
      {
      ...
        "ServiceDiscovery": { "ServiceName": "DataService", "Consul": { "HttpEndpoint": "http://127.0.0.1:8500", "DnsEndpoint": { "Address": "127.0.0.1", "Port": 8600 } } } }

       

      public class ServiceDisvoveryOptions
      {
          public string ServiceName { get; set; } public ConsulOptions Consul { get; set; } } public class ConsulOptions { public string HttpEndpoint { get; set; } public DnsEndpoint DnsEndpoint { get; set; } } public class DnsEndpoint { public string Address { get; set; } public int Port { get; set; } public IPEndPoint ToIPEndPoint() { return new IPEndPoint(IPAddress.Parse(Address), Port); } }
    • 在網站啓動和卸載的時候添加對應註冊和卸載事件
         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.AddDbContext<UserContext>(options => { options.UseMySQL(Configuration.GetConnectionString("MysqlUser")); }); //從配置文件中獲取ServiceDiscovery services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery")); //單例註冊ConsulClient services.AddSingleton<IConsulClient>(p => new ConsulClient(cfg => { var serviceConfiguration = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value; if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint)) { // if not configured, the client will use the default value "127.0.0.1:8500" cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint); } })); services.AddMvc(); //添加受權相關代碼 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect(//配置受權信息相關 "oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:52619";//受權地址 options.RequireHttpsMetadata = false;//ssl證書 options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.ClientId = "MVC"; options.ClientSecret = "Secret"; options.SaveTokens = true; // options.GetClaimsFromUserInfoEndpoint = true;//發起另一個請求~52619/content/userInfo 獲取userinfo //options.ClaimActions.MapJsonKey("sub", "sub"); //options.ClaimActions.MapJsonKey("preferred_username", "preferred_username"); //options.ClaimActions.MapJsonKey("sub", "sub"); //options.ClaimActions.MapJsonKey("avatar", "avatar"); //options.ClaimActions.MapCustomJson("role", jobject => jobject["role"].ToString()); options.Scope.Add("geteway_api"); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("offline_access"); //options.Scope.Add("email");  } );//添加  } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory LoggerFactory, IApplicationLifetime lifetime, IConsulClient consulClient, IOptions<ServiceDisvoveryOptions> DisvoveryOptions) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseAuthentication(); lifetime.ApplicationStarted.Register(() => { RegisterService(app, DisvoveryOptions, consulClient); }); lifetime.ApplicationStopped.Register(() => { DeRegisterService(app, DisvoveryOptions, consulClient); }); UserContextSeed.SeedAsync(app, LoggerFactory).Wait(); //InitUserDataBase(app);//初始化數據庫腳本再建立數據庫以後取消註釋  } //註冊服務方法 private void RegisterService(IApplicationBuilder app, IOptions<ServiceDisvoveryOptions> serviceOptions, IConsulClient consul) { //從當前啓動的url中拿到url var features = app.Properties["server.Features"] as FeatureCollection; var addresses = features.Get<IServerAddressesFeature>() .Addresses .Select(p => new Uri(p)); foreach (var address in addresses) { var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}"; var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1), Interval = TimeSpan.FromSeconds(30), HTTP = new Uri(address, "HealthCheck").OriginalString }; var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, Address = address.Host, ID = serviceId, Name = serviceOptions.Value.ServiceName, Port = address.Port }; consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); } } //移除方法 private void DeRegisterService(IApplicationBuilder app, IOptions<ServiceDisvoveryOptions> serviceOptions, IConsulClient consul) { //從當前啓動的url中拿到url var features = app.Properties["server.Features"] as FeatureCollection; var addresses = features.Get<IServerAddressesFeature>() .Addresses .Select(p => new Uri(p)); foreach (var address in addresses) { var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}"; consul.Agent.ServiceDeregister(serviceId).GetAwaiter().GetResult(); } }  }
  • 服務的發現
    • 添加配置文件(這裏關鍵是ServiceName要對上)
      {
      ...
        "ServiceDiscovery": {
          "ServiceName": "DataService",
          "Consul": {
            "HttpEndpoint": "http://127.0.0.1:8500",
            "DnsEndpoint": {
              "Address": "127.0.0.1",
              "Port": 8600
            }
          }
        }
      }
      public class ServiceDisvoveryOptions
      {
          public string ServiceName { get; set; }
      
          public ConsulOptions Consul { get; set; }
      }
      
      public class ConsulOptions
      {
          public string HttpEndpoint { get; set; }
      
          public DnsEndpoint DnsEndpoint { get; set; }
      }
      
      public class DnsEndpoint
      {
          public string Address { get; set; }
      
          public int Port { get; set; }
      
          public IPEndPoint ToIPEndPoint()
          {
              return new IPEndPoint(IPAddress.Parse(Address), Port);
          }
      }
    • 引用dnsClient nuget包並在ConfigureServices方法中注入相應的實例
               //從配置文件中獲取ServiceDiscovery
                  services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
      
                  services.AddSingleton<IDnsQuery>(p =>
                  {
                      var serviceConfig = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value;//從配置文件中獲取consul相關配置信息
                      return new LookupClient(serviceConfig.Consul.DnsEndpoint.ToIPEndPoint());
                  });
    • 根據配置文件信息去consul中獲取相應的地址
        private readonly string userServiceUrl = "http://localhost:60907/";
      
              public UserService( IOptions<ServiceDisvoveryOptions> option,IDnsQuery dnsQuery)
              {
      var addrs = dnsQuery.ResolveService("service.consul", option.Value.ServiceName);
                  var addressList = addrs.First().AddressList;
                  var host = addressList.Any() ? addressList.First().ToString() : addrs.First().HostName;
                  var port = addrs.First().Port;
                  userServiceUrl = $"http://{host}:{port}";
              }

       

    • 參考自大佬文章 http://michaco.net/blog/ServiceDiscoveryAndHealthChecksInAspNetCoreWithConsul?tag=Consul
相關文章
相關標籤/搜索