ocelot集成consul服务发现

  • 首先下载consul 点击这里下载
  • 转到解压文件夹目录输入cmd命令  consul agent -dev (有时候会卡住按一下方向键上)
  • 在浏览器中输入http://localhost:8500/ui 查看是否安装成功成功如下图所示ocelot集成consul服务发现

     

  • 在网站启动的时候注册服务,网站停止的时候卸载服务。
  • 服务的注册
    • 先引用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
上一篇:[转载]Ocelot简易教程(四)之请求聚合以及服务发现


下一篇:[转载]Ocelot简易教程(二)之快速开始2