/// <summary> /// Instantiates new ConsulAppSettings object using consul agent at specified URI. /// </summary> /// <param name="consulUri">The URI of the Consul agent, ideally should always be on a loopback address i.e localhost</param> /// <param name="setSpecificity">Logic used when using Set command</param> public ConsulAppSettings(string consulUri, KeySpecificity setSpecificity = KeySpecificity.Instance) { consulUri.ThrowIfNullOrEmpty(nameof(consulUri)); this.consulUri = consulUri; keyValueEndpoint = consulUri.CombineWith("/v1/kv/"); this.setSpecificity = setSpecificity; }
/// <summary> /// Creates a formatted lookup for the hierarchical specificity /// </summary> /// <param name="key">the key name</param> /// <param name="specificity">the key specificity</param> /// <returns>the formatted key</returns> /// <exception cref="InvalidOperationException">Thrown if a version specific key is requested but no version has been set in the <see cref="HostConfig.ApiVersion"/></exception> public static string GetKeyForSpecificity(string key, KeySpecificity specificity) { if (specificity == KeySpecificity.LiteralKey) { return(key); } var globalKey = !key.StartsWith(Prefix) ? GetDefaultLookupKey(key) : key; if (specificity == KeySpecificity.Global) { return(globalKey); // global (ss/keyname) } var appHost = HostContext.AppHost; var serviceName = appHost.ServiceName; var serviceKey = $"{globalKey}/{serviceName}"; if (specificity == KeySpecificity.Service) { return(serviceKey); // service specific (ss/keyname/service) } if (specificity == KeySpecificity.Instance) { var instanceId = GetInstanceId(appHost.Config); return($"{serviceKey}/i/{instanceId}"); // instance specific (ss/keyname/service/127.0.0.1:8080) } if (string.IsNullOrWhiteSpace(appHost.Config?.ApiVersion)) { throw new InvalidOperationException("Unable to get Version specific key when Version not set"); } var version = appHost.Config.ApiVersion.Replace("/", "."); return($"{serviceKey}/{version}"); // version specific (ss/keyname/service/v1) }
/// <summary> /// Instantiates new ConsulAppSettings object using local consul agent (http://127.0.0.1:8500) /// </summary> /// <param name="setLevel">Logic used when using Set command</param> public ConsulAppSettings(KeySpecificity setLevel = KeySpecificity.Instance) : this(ConsulLocalhostUri, setLevel) { }
public void Set_Respects_KeySpecificity(KeySpecificity keySpecificity, string expectedKey) { var keySpecificAppSetting = new ConsulAppSettings(keySpecificity); VerifySetEndpoint(() => keySpecificAppSetting.Set(SlashKey, 123), "true", expectedKey); }
/// <summary> /// Instantiates new ConsulAppSettings object using local consul agent (http://127.0.0.1:8500) /// </summary> /// <param name="setLevel">Logic used when using Set command</param> public ConsulAppSettings(KeySpecificity setLevel = KeySpecificity.Instance) : this("http://127.0.0.1:8500", setLevel) { }