Example #1
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifeTime)
        {
            //if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();
            //else
            //    //使用全局异常捕获,并在error页面呈现
            //    app.UseExceptionHandler("/message/error");

            //使访问支持静态内容返回,不加这句话图片等静态资源都返回不了
            app.UseStaticFiles();
            //启用上传下载删除文件功能
            app.UseUpload();
            app.UseDownload();
            app.UseRemoveFile();
            //启用心跳包功能
            app.UseHealth();
            //把appsetting的配置加载到context.items["AppSetting"]中
            app.UseAppSetting();


            //var log=app.ApplicationServices.GetRequiredService<ILoggerFactory>().AddConsole().CreateLogger("aa");
            app.UseMvc(routes => routes.MapRoute(
                           name: "default",
                           template: "{controller=Home}/{action=Index}/{id?}"));

            //启用swagger
            var swaggerdoc = new OptionsSwagger();

            Configuration.GetSection("OptionsSwagger").Bind(swaggerdoc);
            app.UseSwagger(swaggerdoc);


            //发现服务(consul等)的配置文件
            var serviceInfo = new OptionsServiceInfo();

            Configuration.GetSection("OptionsServiceInfo").Bind(serviceInfo);
            //心跳包的配置文件
            var health = new OptionsHealth();

            Configuration.GetSection("OptionsHealth").Bind(health);
            //执行服务注册到服务发现中心(consul等)
            app.ExecServiceRegister(appLifeTime, serviceInfo, health);
        }
Example #2
0
        public void Register(IApplicationLifetime lifetime, OptionsServiceInfo serviceInfo, OptionsHealth health)
        {
            if (!serviceInfo.Enable)
            {
                return;
            }
            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceInfo.RegisterIP}:{serviceInfo.RegisterPort}"));//请求注册的 Consul 地址
            var httpCheck    = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),                              //服务启动多久后注册
                Interval = TimeSpan.FromSeconds(serviceInfo.Interval),                                 //健康检查时间间隔,或者称为心跳间隔
                HTTP     = $"http://{serviceInfo.ServiceIP}:{serviceInfo.ServicePort}{health.Router}", //健康检查地址
                Timeout  = TimeSpan.FromSeconds(5)
            };

            // Register service with consul
            var registration = new AgentServiceRegistration()
            {
                Checks  = new[] { httpCheck },
                ID      = Guid.NewGuid().ToString(),
                Name    = serviceInfo.ServiceName,
                Address = serviceInfo.ServiceIP,
                Port    = serviceInfo.ServicePort,
                Tags    = new[] { $"urlprefix-/{serviceInfo.ServiceName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
            };

            try
            {
                consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
                lifetime.ApplicationStopping.Register(() =>
                {
                    consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
                });
            }
            catch (Exception ex)
            {
                log.InfoAsync("注册到Consul异常:" + ex.Message);
            }
        }
        /// <summary>
        /// 执行服务注册
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static void ExecServiceRegister(this IApplicationBuilder app, IApplicationLifetime lifetime, OptionsServiceInfo serviceInfo, OptionsHealth health)
        {
            if (serviceInfo == null || health == null)
            {
                return;
            }
            if (string.IsNullOrEmpty(serviceInfo.ServiceName) || string.IsNullOrEmpty(health.Router))
            {
                return;
            }
            serviceInfo.ServiceIP = Common.Share.IPHelper.GetNetWork(serviceInfo.ServiceIP);

            IServiceRegisterProvider provider = new ConsulProvider();//todo:后续要改成工厂

            provider.Register(lifetime, serviceInfo, health);
        }