各种权重策略
作者:互联网
分别为 平均算法 、权重、轮询
/// <summary> /// 平均 /// </summary> /// <returns></returns> protected override int GetIndex() {
//直接使用random会因为种子的问题使查询很有可能一致,所以增加 iTotalCount 控制种子
return new Random(iTotalCount++).Next(0, base._CurrentAgentServiceDictionary.Length); }
权重
#region Identity private static int _iTotalCount = 0; private static int iTotalCount { get { return _iTotalCount; } set { _iTotalCount = value >= Int32.MaxValue ? 0 : value; } } public WeightDispatcher(IOptionsMonitor<ConsulClientOptions> consulClientOption) : base(consulClientOption) { } #endregion protected override string ChooseAddress(string serviceName) { ConsulClient client = new ConsulClient(c => { c.Address = new Uri($"http://{base._ConsulClientOption.IP}:{base._ConsulClientOption.Port}/"); c.Datacenter = base._ConsulClientOption.Datacenter; }); AgentService agentService = null; var response = client.Agent.Services().Result.Response; this._CurrentAgentServiceDictionary = response.Where(s => s.Value.Service.Equals(serviceName, StringComparison.OrdinalIgnoreCase)).ToArray(); var serviceDictionaryNew = new List<AgentService>(); foreach (var service in base._CurrentAgentServiceDictionary) { serviceDictionaryNew.AddRange(Enumerable.Repeat(service.Value, int.TryParse(service.Value.Tags?[0], out int iWeight) ? 1 : iWeight)); } int index = new Random(DateTime.Now.Millisecond).Next(0, int.MaxValue) % serviceDictionaryNew.Count; agentService = serviceDictionaryNew[index]; return $"{agentService.Address}:{agentService.Port}"; }
轮询、//使用初始变量为0 每次取余
#region Identity private static int _iTotalCount = 0; private static int iTotalCount { get { return _iTotalCount; } set { _iTotalCount = value >= Int32.MaxValue ? 0 : value; } } public PollingDispatcher(IOptionsMonitor<ConsulClientOptions> consulClientOption) : base(consulClientOption) { } #endregion /// <summary> /// 轮询 /// </summary> /// <param name="serviceCount"></param> /// <returns></returns> protected override int GetIndex() { return iTotalCount++ % base._CurrentAgentServiceDictionary.Length; }
标签:各种,return,策略,权重,int,base,iTotalCount,._,new 来源: https://www.cnblogs.com/YZM97/p/15811041.html