public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceEntity entity) { //请求注册的consul地址 var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{entity.ConsulIP}:{entity.ConsulPort}")); var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), Interval = TimeSpan.FromSeconds(10), HTTP = $"Http://{entity.IP}:{entity.Port}/api/health/index", Timeout = TimeSpan.FromSeconds(5) }; //注册到consul var reagistration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, ID = Guid.NewGuid().ToString(), Name = entity.ServiceName, Address = entity.IP, Port = entity.Port, Tags = new[] { $"urlprefix-/{entity.ServiceName}" } }; //服务启动时注册,内部实际由consul api注册 httpClient发起 consulClient.Agent.ServiceRegister(reagistration).Wait(); lifetime.ApplicationStopped.Register(() => { consulClient.Agent.ServiceDeregister(reagistration.ID).Wait(); }); return(app); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime) { ServiceEntity serviceEntity = new ServiceEntity { IP = Configuration["Service:IP"], Port = Convert.ToInt32(Configuration["Service:Port"]), ServiceName = Configuration["Service:Name"], ConsulIP = Configuration["Consul:IP"], ConsulPort = Convert.ToInt32(Configuration["Consul:Port"]) }; Console.WriteLine($"consul开始注册{JsonConvert.SerializeObject(serviceEntity)}"); app.RegisterConsul(lifetime, serviceEntity); //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} //app.UseRouting(); //微服务中的各个swagger名称 var apis = new List <string> { "UserService" }; app.UseMvc() .UseSwagger() .UseSwaggerUI(options => { apis.ForEach(m => options.SwaggerEndpoint($"/{m}/swagger.json", m) ); }); //app.UseEndpoints(endpoints => //{ // endpoints.MapGet("/", async context => // { // await context.Response.WriteAsync("Hello World!"); // }); //}); app.UseOcelot().Wait();//ocelot请求管道 //MvcOptions m = new MvcOptions(); //m.EnableEndpointRouting = false; }