LoadBalancingForApiNode.cs 1.7 KB

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