예제 #1
0
        // 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();
            }

            app.UseMvc();

            var config = new ConsulConfiguration
            {
                IP          = Configuration["Service:Name"],
                Port        = Program.Port,
                ServiceName = Configuration["Service:Name"],
                ConsulIP    = Configuration["Consul:IP"],
                ConsulPort  = Convert.ToInt32(Configuration["Consul:Port"])
            };


            app.RegisterConsul(lifetime, config);
        }
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, ConsulConfiguration consulConfig)
        {
            Console.WriteLine($"Consul config -> http://{consulConfig.ConsulIP}:{consulConfig.ConsulPort}");
            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulConfig.ConsulIP}:{consulConfig.ConsulPort}"));
            var httpCheck    = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                Interval = TimeSpan.FromSeconds(10),
                HTTP     = $"http://{consulConfig.IP}:{consulConfig.Port}/api/health",
                Timeout  = TimeSpan.FromSeconds(5)
            };

            // Register service with consul
            var registration = new AgentServiceRegistration()
            {
                Checks  = new[] { httpCheck },
                ID      = Guid.NewGuid().ToString(),
                Name    = consulConfig.ServiceName,
                Address = consulConfig.IP,
                Port    = consulConfig.Port,
                Tags    = new[] { $"urlprefix-/{consulConfig.ServiceName}" }
            };

            consulClient.Agent.ServiceRegister(registration).Wait();
            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            });

            return(app);
        }