using Consul; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Yi.Framework.Common.IOCOptions; namespace Yi.Framework.Core.Consul { public abstract class AbstractConsulDispatcher { protected ConsulClientOption _ConsulClientOption = null; protected KeyValuePair[] _CurrentAgentServiceDictionary = null; public AbstractConsulDispatcher(IOptionsMonitor consulClientOption) { _ConsulClientOption = consulClientOption.CurrentValue; } /// /// 负载均衡获取地址 /// /// Consul映射后的地址 /// public string GetAddress(string mappingUrl) { Uri uri = new Uri(mappingUrl); string serviceName = uri.Host; string addressPort = ChooseAddress(serviceName); return $"{uri.Scheme}://{addressPort}{uri.PathAndQuery}"; } protected virtual string ChooseAddress(string serviceName) { ConsulClient client = new ConsulClient(c => { c.Address = new Uri($"http://{_ConsulClientOption.IP}:{_ConsulClientOption.Port}/"); c.Datacenter = _ConsulClientOption.Datacenter; }); AgentService agentService = null; //var response = client.Agent.Services().Result.Response; ////foreach (var item in response) ////{ //// Console.WriteLine("***************************************"); //// Console.WriteLine(item.Key); //// var service = item.Value; //// Console.WriteLine($"{service.Address}--{service.Port}--{service.Service}"); //// Console.WriteLine("***************************************"); ////} //this._CurrentAgentServiceDictionary = response.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToArray(); //升级consul实例获取 var entrys = client.Health.Service(serviceName).Result.Response; List> serviceList = new List>(); for (int i = 0; i < entrys.Length; i++) { serviceList.Add(new KeyValuePair(i.ToString(), entrys[i].Service)); } _CurrentAgentServiceDictionary = serviceList.ToArray(); int index = GetIndex(); agentService = _CurrentAgentServiceDictionary[index].Value; return $"{agentService.Address}:{agentService.Port}"; } protected abstract int GetIndex(); } }