LoadBalancingForApiNode.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using Sers.Core.Module.Api.ApiDesc;
  5. using Sers.ServiceCenter.Entity;
  6. using Vit.Core.Module.Log;
  7. namespace Sers.Gover.Base.Model
  8. {
  9. public class LoadBalancingForApiNode
  10. {
  11. /// <summary>
  12. /// TODO:待完善
  13. /// </summary>
  14. public SsApiDesc apiDesc => apiNodes[0]?.apiDesc;
  15. List<ApiNode> apiNodes = new List<ApiNode>();
  16. private int _apiNodeCount;
  17. public int apiNodeCount => _apiNodeCount;
  18. int curIndex = -1;
  19. public ApiNode GetCurApiNodeBalancing()
  20. {
  21. //TODO: 负载均衡的实现
  22. int cur = Interlocked.Increment(ref curIndex);
  23. try
  24. {
  25. if (cur >= (int.MaxValue - 10000))
  26. {
  27. cur = curIndex = 0;
  28. }
  29. else
  30. {
  31. cur %= _apiNodeCount;
  32. }
  33. return apiNodes[cur];
  34. }
  35. catch (Exception ex)
  36. {
  37. //TODO: not expected
  38. Logger.Error(ex);
  39. throw;
  40. }
  41. }
  42. public void AddApiNode(ApiNode apiNode)
  43. {
  44. apiNodes.Insert(0, apiNode);
  45. _apiNodeCount = apiNodes.Count;
  46. }
  47. public void RemoveApiNode(ApiNode apiNode)
  48. {
  49. apiNodes.Remove(apiNode);
  50. _apiNodeCount = apiNodes.Count;
  51. }
  52. }
  53. }