예제 #1
0
        // 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,
            ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            //var address = Configuration.GetValue<string>("urls");
            var address = Configuration["urls"];
            var logger  = loggerFactory.CreateLogger("TestInfo");

            var addArr = address.Split(':');
            var Port   = Convert.ToInt32(addArr[2]);
            var IP     = addArr[1].Substring(2);

            ConsulOption consulOption = new ConsulOption()
            {
                ServiceName   = Configuration["servicename"],
                IP            = IP,
                Port          = Port,
                ConsulAddress = Configuration["consuladdress"]
            };

            logger.LogWarning($"Consul {consulOption.ServiceName} at {consulOption.ConsulAddress}");
            logger.LogWarning($"Consul {consulOption.ServiceName}'s local service at {address}");

            app.UseConsul(lifetime, consulOption);
        }
예제 #2
0
        public static IApplicationBuilder UseConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ConsulOption option)
        {
            var consulClient = new ConsulClient(t =>
            {
                t.Address = new Uri("http://localhost:8500");
            });

            var healthCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),       //服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),                            //健康检查时间间隔,或者称为心跳间隔
                HTTP     = $"http://{option.IP}:{option.Port}/api/HealthCheck", //健康检查地址
                Timeout  = TimeSpan.FromSeconds(50)
            };

            var registConsul = new AgentServiceRegistration()
            {
                //Checks = new[] { healthCheck },
                Check   = healthCheck,
                ID      = Guid.NewGuid().ToString(),
                Name    = option.ServiceName,
                Address = option.IP,
                Port    = option.Port,
                Tags    = new[] { $"urlprefix-/{option.ServiceName}" },
            };

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

            return(app);
        }