public bool ChoiceLoad(ServiceManager.Agent.SubscribeState providers, out long provider) { provider = 0; var list = providers.ServiceInfos.ServiceInfoListSortedByIdentity; var frees = new List <ProviderSession>(list.Count); var all = new List <ProviderSession>(list.Count); int TotalWeight = 0; // 新的provider在后面,从后面开始搜索。后面的可能是新的provider。 for (int i = list.Count - 1; i >= 0; --i) { var providerModuleState = list[i].LocalState as ProviderModuleState; if (null == providerModuleState) { continue; } var ps = App.Instance.ProviderService.GetSocket(providerModuleState.SessionId)?.UserState as ProviderSession; if (null == ps) { continue; // 这里发现关闭的服务,仅仅忽略. } all.Add(ps); if (ps.OnlineNew > App.Instance.Config.MaxOnlineNew) { continue; } int weight = ps.ProposeMaxOnline - ps.Online; if (weight <= 0) { continue; } frees.Add(ps); TotalWeight += weight; } if (TotalWeight > 0) { int randweight = Zeze.Util.Random.Instance.Next(TotalWeight); foreach (var ps in frees) { int weight = ps.ProposeMaxOnline - ps.Online; if (randweight < weight) { provider = ps.SessionId; return(true); } randweight -= weight; } } // 选择失败,一般是都满载了,随机选择一个。 if (all.Count > 0) { provider = all[Zeze.Util.Random.Instance.Next(all.Count)].SessionId; return(true); } // no providers return(false); }
public bool ChoiceHash(ServiceManager.Agent.SubscribeState providers, int hash, out long provider) { provider = 0; var list = providers.ServiceInfos.ServiceInfoListSortedByIdentity; if (list.Count == 0) { return(false); } var providerModuleState = list[hash % list.Count].LocalState as ProviderModuleState; if (null == providerModuleState) { return(false); } provider = providerModuleState.SessionId; return(true); }