示例#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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            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);
        }
示例#2
0
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime 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}/home/health",
                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);
        }