/// <summary> /// Queries the local Consul agent for healthy instances of a given service and selects one such instance. /// </summary> /// <param name="query">Query used to find services instances.</param> /// <exception cref="NoAvailableServiceInstanceException">Thrown when there is no healthy instance available for that service.</exception> /// <returns>Returns a service instance.</returns> public ServiceInstanceDescriptor GetServiceInstance(ServiceInstanceQuery query, ServiceInstanceSelectionStrategy?strategy = null) { IServiceInstanceSelectionStrategy selectionStrategy = null; if (strategy.HasValue) { selectionStrategy = InitializeServiceInstanceSelectionStrategy(strategy.Value); } else { selectionStrategy = DefaultServiceInstanceSelectionStrategy; } if (selectionStrategy == null) { throw new MagellanException("Could not initialize any service instance selection strategy."); } //Query for available instances ICollection <ServiceInstanceDescriptor> availableInstances = GetServiceInstances(query); //Select instance if (availableInstances.Count > 0) { return(selectionStrategy.SelectServiceInstance(availableInstances)); } else { throw new NoAvailableServiceInstanceException(); } }
/// <summary> /// Sets up the Magellan client with all needed configuration options. /// </summary> /// <param name="configuration">The configuration for the Magellan client.</param> public MagellanClient(MagellanClientConfiguration configuration) { //Set default service selection strategy DefaultServiceInstanceSelectionStrategy = InitializeServiceInstanceSelectionStrategy(configuration.DefaultServiceInstanceSelectionStrategy); //Initialize Consul client Consul = new ConsulClient(consulClientConfig => { consulClientConfig.Address = new Uri($"http://{configuration.ConsulAgentHost}:{configuration.ConsulAgentPort.ToString()}"); }); }
/// <summary> /// Initializes a service instance selection strategy object. /// </summary> /// <param name="strategyType">Type of strategy to initialize an object for.</param> /// <returns>Returns a service selection strategy.</returns> private IServiceInstanceSelectionStrategy InitializeServiceInstanceSelectionStrategy(ServiceInstanceSelectionStrategy strategyType) { IServiceInstanceSelectionStrategy strategy = null; switch (strategyType) { case ServiceInstanceSelectionStrategy.RandomServiceInstanceSelection: strategy = new RandomServiceInstanceSelectionStrategy(); break; default: throw new NotImplementedException($"No implementation available for service instance selection strategy {strategyType}."); } return(strategy); }