/// <summary>
 ///     Adds Consul as a configuration source to the <see cref="IConfigurationBuilder" />
 ///     using the default settings in <see cref="IConsulConfigurationSource" />.
 /// </summary>
 /// <param name="builder">The builder to add consul to.</param>
 /// <param name="key">The key in consul where the configuration is located.</param>
 /// <param name="cancellationToken">
 ///     The <see cref="CancellationToken" /> used to cancel any open Consul connections or
 ///     watchers.
 /// </param>
 /// <returns>The builder</returns>
 public static IConfigurationBuilder AddConsul(
     this IConfigurationBuilder builder,
     string key,
     CancellationToken cancellationToken)
 {
     return(builder.AddConsul(key, cancellationToken, options => { }));
 }
        public static IConfigurationBuilder ConsulUseAppConfiguration(this IConfigurationBuilder builder, HostBuilderContext ctx, string[] args)
        {
            var env = ctx.HostingEnvironment;

            var cfg = new ConfigurationBuilder()
                      .AddJsonFile("appsettings.json")
                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json")
                      .AddEnvironmentVariables()
                      .Build();

            var consulHost = cfg.GetSection(ConsulHostSection).Value;
            var consulApp  = cfg.GetSection(ConsulAppSection).Value;

            builder.AddConsul($"{consulApp}/appsettings.json",
                              options =>
            {
                options.ConsulConfigurationOptions =
                    cco => { cco.Address = new Uri(consulHost); };
                options.Optional        = true;
                options.ReloadOnChange  = true;
                options.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; };
                options.PollWaitTime    = TimeSpan.FromSeconds(1);
            }
                              )
            .AddEnvironmentVariables()
            .AddCommandLine(args);
            ;

            return(builder);
        }
Esempio n. 3
0
        public static void ConsulApplicationConfiguration(HostBuilderContext builderContext,
                                                          IConfigurationBuilder configurationBuilder)
        {
            var env = builderContext.HostingEnvironment;


            configurationBuilder.AddConsul(
                $"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json",
                options =>
            {
                options.Optional                   = true;
                options.ReloadOnChange             = true;
                options.OnLoadException            = exceptionContext => { exceptionContext.Ignore = true; };
                options.ConsulConfigurationOptions = consulConfig =>
                {
                    var consulUrl = Environment.GetEnvironmentVariable("CONSUL_CONFIG_CENTER_URL");
                    var consulDc  = Environment.GetEnvironmentVariable("CONSUL_CONFIG_CENTER_DC");

                    consulConfig.Address    = new Uri(consulUrl == "" ? "" : consulUrl);
                    consulConfig.Datacenter = consulDc == "" ? "dc1" : consulDc;
                };
            });

            builderContext.Configuration = configurationBuilder.Build();
        }
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, ConsulClient consulClient, string path = "/")
 {
     return(builder.AddConsul(s =>
     {
         s.ConsulClient = consulClient;
     }));
 }
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, Action <ConsulClientConfiguration> clientConfigure, Action <ConsulConfigurationSource> configureSource)
 {
     return(builder.AddConsul(s =>
     {
         s.ConsulClient = new ConsulClient(clientConfigure);
         configureSource?.Invoke(s);
     }));
 }
 public void AddConfigToConsul(string key, CancellationTokenSource consulCancellationTokenSource)
 {
     _configurationBuilder.AddConsul(
         $"{_configuration["ASPNETCORE_ENVIRONMENT"]}/{_configuration["ServiceConfig:serviceName"]}/{key}",
         consulCancellationTokenSource.Token,
         ConsulClientOptions
         );
 }
Esempio n. 7
0
 public static void getbuild(IConfigurationBuilder builder, string key)
 {
     builder.AddConsul(string.IsNullOrEmpty(key) ? "appsettings.json" : key, (soure) =>
     {
         soure.ConsulConfigurationOptions = PZConsul;
         //热加载  实时刷新consul中的配置中心
         soure.ReloadOnChange = true;
     });
 }
Esempio n. 8
0
        public static IConfigurationBuilder AddConsul(
            this IConfigurationBuilder builder,
            ConfigurationOptions options,
            Action <IConsulHandler> configure
            )
        {
            var handler = new ConsulHandler();

            configure.Invoke(handler);
            return(builder.AddConsul(options, handler));
        }
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, Uri address, string path = "/", string datacenter = null)
 {
     return(builder.AddConsul(c =>
     {
         c.Address = address;
         c.Datacenter = datacenter;
     }, s =>
     {
         s.Path = path;
     }));
 }
Esempio n. 10
0
        public static IConfigurationBuilder AddConsul(this IConfigurationBuilder configurationBuilder, string[] args)
        {
            var dic = ParseCommandLineArgs(args);

            return(configurationBuilder.AddConsul(new ConsulClientConfiguration
            {
                Address = new Uri(dic.GetDictionaryValue("consul-configuration-addr", "http://127.0.0.1:8500")),
                Token = dic.GetDictionaryValue("consul-configuration-token"),
                Datacenter = dic.GetDictionaryValue("consul-configuration-dc", "dc1"),
                WaitTime = TimeSpan.FromSeconds(10)
            }, dic.GetDictionaryValue("consul-configuration-folder")));
        }
        public static void ConsulConfig(this IConfigurationBuilder context)
        {
            var configuration = context.Build();
            var consulConfig  = configuration.GetSection(nameof(ConsulConfig)).Get <ConsulConfig>();

            if (consulConfig == null || consulConfig.Urls == null || consulConfig.Urls.Count == 0)
            {
                throw new ArgumentNullException("can not find consul config");
            }

            context.AddConsul(consulConfig);
        }
        public static IConfigurationBuilder PrepareBuilder(this IConfigurationBuilder configurationBuilder)
        {
            var url      = KVServerUrl.Get();
            var audience = Audience.Get();
            var stage    = StageName.Get();

            if (url != null)
            {
                var path = audience != null ? $"{audience}/{stage}" : stage;

                configurationBuilder.AddConsul(url, path, true, true);
            }

            return(configurationBuilder);
        }
Esempio n. 13
0
        public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, CancellationToken cancellationToken)
        {
            // 获取服务配置项
            var consulOptions = AppConfig.GetSection <ConsulServiceOptions>("Consul");

            return(builder.AddConsul(AppConfig.ServerOptions.Name, cancellationToken, source =>
            {
                source.ConsulClientConfiguration = cco => cco.Address = new Uri(consulOptions.ConsulAddress);
                source.Optional = true;
                source.ReloadOnChange = true;
                source.ReloadDelay = 300;
                source.QueryOptions = new QueryOptions
                {
                    WaitIndex = 0
                };
            }));
        }
        private IConfigurationRoot ConfigureConsul(IConfigurationBuilder cb)
        {
            IEnumerable <string> consulAddresses = _configuration.GetSection("consulSettings:host").GetChildren().Select(x => x.Value);
            string consulPath  = _configuration.GetValue <string>("consulSettings:path");
            int    consulTimer = _configuration.GetValue <int>("consulSettings:watchDelay");
            string aclToken    = _configuration.GetValue <string>("consulSettings:accessToken");

            if (!consulAddresses.Any() || string.IsNullOrWhiteSpace(consulPath))
            {
                throw new ApplicationException("no consul endpoints provided!");
            }
            if (consulTimer < 10000)
            {
                throw new ApplicationException("consul fail delay timer must be at least ten seconds!");
            }
            cb.AddConsul(consulAddresses, consulPath, consulTimer, aclToken, _logger);
            return(cb.Build());
        }
Esempio n. 15
0
        public static void ConfigureAppConfiguration(WebHostBuilderContext hostingContext, IConfigurationBuilder builder)
        {
            var env = hostingContext.HostingEnvironment;

            builder
            .AddConsul($"{env.ApplicationName}.{env.EnvironmentName}",
                       cancellationTokenSource.Token,
                       options => {
                options.ConsulConfigurationOptions =
                    cco => {
                    cco.Address    = new Uri("http://localhost:8500");
                    cco.Datacenter = "dc1";
                };
                options.Optional        = true;
                options.ReloadOnChange  = true;
                options.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; };
            })
            .AddEnvironmentVariables();
        }
Esempio n. 16
0
        public static IConfigurationBuilder AddConsul(
            this IConfigurationBuilder builder,
            ConfigurationOptions configurationOptions,
            IConsulHandler consulHandler,
            ILoggerFactory?loggerFactory
            )
        {
            var consulBuilder  = new ConsulBuilder(consulHandler);
            var consulEndpoint = new ConsulKvEndpoint(consulBuilder, loggerFactory.CreateLogger <ConsulKvEndpoint>())
            {
                WatchExceptionHandler = async(kv, e, key, logger, ct) =>
                {
                    await Task.Delay(10000, ct);

                    logger.LogWarning($"Restart watching {key}");
                    return(true);
                }
            };

            return(builder.AddConsul(configurationOptions, consulHandler, consulEndpoint));
        }
Esempio n. 17
0
        /// <summary>
        /// 添加Consul配置中心
        /// </summary>
        /// <param name="builder">配置生成器</param>
        /// <param name="options">选项回调</param>
        /// <returns>配置生成器</returns>
        public static IConfigurationBuilder AddConsulConfigCenter(this IConfigurationBuilder builder, Action <ConfigCenterOptions> options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("回调配置不能为null");
            }
            var configOptions = new ConfigCenterOptions();

            options(configOptions);
            if (string.IsNullOrWhiteSpace(configOptions.ConsulAddress))
            {
                throw new ArgumentNullException("Consul地址不能为空");
            }
            if (configOptions.Keys.IsNullOrCount0())
            {
                throw new ArgumentNullException("键不能为空");
            }

            Action <IConsulConfigurationSource> fun = delegate(IConsulConfigurationSource source)
            {
                source.ConsulConfigurationOptions = cco =>
                {
                    // 配置Consul
                    cco.Address    = new Uri(configOptions.ConsulAddress);
                    cco.Datacenter = configOptions.Datacenter;
                };
                source.Optional        = true;                                                    // 配置选项
                source.ReloadOnChange  = true;                                                    // 配置文件更新后重新加载
                source.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; }; // 忽略异常
            };

            foreach (var key in configOptions.Keys)
            {
                builder.AddConsul(key, fun);
            }

            return(builder);
        }
Esempio n. 18
0
 public static IConfigurationBuilder AddConsul(
     this IConfigurationBuilder builder,
     string prefix,
     string separator,
     string watch,
     CancellationToken cancellationToken,
     Action <ConsulClientConfiguration> clientConfig
     )
 {
     return(builder.AddConsul(
                new ConfigurationOptions
     {
         Prefix = prefix,
         Separator = separator,
         Watch = watch
     },
                c =>
     {
         c.ClientConfigurationOptions = clientConfig;
         c.CancellationToken = cancellationToken;
     }
                ));
 }
Esempio n. 19
0
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder configurationBuilder, IEnumerable <string> consulUrls, string consulPath)
 {
     return(configurationBuilder.AddConsul(consulUrls.Select(u => new Uri(u)), consulPath));
 }
Esempio n. 20
0
 public static IConfigurationBuilder AddConsul(
     this IConfigurationBuilder builder,
     ConfigurationOptions configurationOptions,
     IConsulHandler consulHandler
     ) =>
 builder.AddConsul(configurationOptions, consulHandler, (ILoggerFactory?)null);
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder configurationBuilder, ConsulConfig consulConfig)
 {
     return(configurationBuilder.AddConsul(consulConfig.Urls, consulConfig.KeyStoreFolder));
 }
Esempio n. 22
0
        public void When_no_prefix_is_specified()
        {
            _builder.AddConsul();

            _builder.Received().Add(Arg.Is <ConsulConfigurationSource>(source => source.Prefix == string.Empty));
        }
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, string url, string path = "/", string datacenter = null)
 {
     return(builder.AddConsul(new Uri(url), path, datacenter));
 }
 public static IConfigurationBuilder AddConsul(this IConfigurationBuilder builder, string key)
 {
     return(builder.AddConsul(key, options => { }));
 }
Esempio n. 25
0
        static void ConfigureConsul(
            this IConfiguration configuration,
            IConfigurationBuilder configBuilder,
            ConsulConfigurationOptions?configOptions,
            IHostEnvironment env)
        {
            // Применяем переменную APPLICATION_NAME из переменных среды,
            // если она не задана, то используем встроенное значение env.ApplicationName.
            var applicationName = env.ApplicationName;

            if (!string.IsNullOrEmpty(configuration[ApplicationNameEnv]))
            {
                applicationName = configuration[ApplicationNameEnv];
            }

            configOptions ??= new ConsulConfigurationOptions();

            // Если находимся в DEV, то используем appsettings.development.json
            if (env.IsDevelopment())
            {
                return;
            }

            // Загружаем конфигурацию подключения в Consul из примонтированного файла.
            var consulConfigFile = ConsulConfigFileDefault;

            if (!File.Exists(ConsulConfigFileDefault) && !string.IsNullOrEmpty(configuration[ConsulConfigFileEnv]))
            {
                Console.WriteLine("Consul connection file detected by environment variable.");
                consulConfigFile = configuration[ConsulConfigFileEnv];
            }
            configBuilder.AddJsonFile(consulConfigFile, optional: false, reloadOnChange: false);

            var consulClientConfiguration = new ConsulClientConfiguration();

            var consulBuilder = new ConfigurationBuilder();

            consulBuilder.SetBasePath(env.ContentRootPath);
            consulBuilder.AddJsonFile(consulConfigFile, optional: false, reloadOnChange: false);

            var consulConfig = consulBuilder.Build();

            if (string.IsNullOrEmpty(consulConfig[ConsulConfigFileSectionName + ":Address"]))
            {
                throw new ConsulConfigurationException($"Failed to load Consul server address from {consulConfigFile}. The wrong data format may have been used.");
            }

            var consulRoot = env.EnvironmentName?.ToLower();

            if (!string.IsNullOrEmpty(consulConfig[ConsulConfigFileSectionName + ":RootFolder"]))
            {
                consulRoot = consulConfig[ConsulConfigFileSectionName + ":RootFolder"].ToLower();
            }

            consulConfig
            .GetSection(ConsulConfigFileSectionName)
            .Bind(consulClientConfiguration);

            var appsettingsFileName = string.IsNullOrEmpty(configOptions.AppsettingsFileName) ? AppsettingsFile : configOptions.AppsettingsFileName;

            if (configOptions.UseCommonAppsettings)
            {
                var commonAppsettingsFileName = string.IsNullOrEmpty(configOptions.CommonAppsettingsFileName) ? CommonAppsettingsFile : configOptions.CommonAppsettingsFileName;
                configBuilder
                .AddConsul(
                    $"{consulRoot}/{commonAppsettingsFileName}",
                    options => ConfigureConsulOptions(options, consulClientConfiguration));
            }
            // Включение конфигурации для микросервиса.
            configBuilder
            .AddConsul(
                $"{consulRoot}/{applicationName?.ToLower()}/{appsettingsFileName}",
                options => ConfigureConsulOptions(options, consulClientConfiguration));
        }