ApiLoadBalancingMng.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Runtime.CompilerServices;
  4. using Sers.Core.Module.Api.ApiDesc;
  5. using Sers.Core.Module.Api.RouteMap;
  6. using Sers.Core.Module.Rpc;
  7. using Sers.Gover.Base.Model;
  8. using Sers.ServiceCenter.Entity;
  9. namespace Sers.Gover.Base
  10. {
  11. /// <summary>
  12. /// 当前可调用的ApiService
  13. /// </summary>
  14. public class ApiLoadBalancingMng
  15. {
  16. public ApiLoadBalancingMng()
  17. {
  18. }
  19. protected readonly RouteMap<LoadBalancingForApiNode> routeMap = new RouteMap<LoadBalancingForApiNode>();
  20. public IEnumerable<SsApiDesc> GetAllApiDesc()
  21. {
  22. return routeMap.GetAll().Select((m) => m.apiDesc);
  23. }
  24. /// <summary>
  25. /// 通过负载均衡算法 获取可调用的ApiNode
  26. /// </summary>
  27. /// <param name="rpcData"></param>
  28. /// <param name="routeType"></param>
  29. /// <returns></returns>
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. public virtual ApiNode GetCurApiNodeByLoadBalancing(RpcContextData rpcData, out ERouteType routeType)
  32. {
  33. return routeMap.Routing(rpcData.route, out routeType)?.GetCurApiNodeBalancing();
  34. }
  35. protected virtual string GetApiRoute(ApiNode apiNode)
  36. {
  37. return apiNode.apiDesc.route;
  38. }
  39. public void ApiNode_Add(ApiNode apiNode)
  40. {
  41. lock (this)
  42. {
  43. var route = GetApiRoute(apiNode);
  44. if (string.IsNullOrWhiteSpace(route)) return;
  45. var lbApiNode = routeMap.Get(route);
  46. if (null == lbApiNode)
  47. {
  48. lbApiNode = new LoadBalancingForApiNode();
  49. routeMap.Set(route, lbApiNode);
  50. }
  51. lbApiNode.AddApiNode(apiNode);
  52. }
  53. }
  54. public void ApiNode_Remove(ApiNode apiNode)
  55. {
  56. lock (this)
  57. {
  58. var route = GetApiRoute(apiNode);
  59. if (string.IsNullOrWhiteSpace(route)) return;
  60. var lbApiNode = routeMap.Get(route);
  61. if (null == lbApiNode)
  62. {
  63. return;
  64. }
  65. lbApiNode.RemoveApiNode(apiNode);
  66. if (0 == lbApiNode.apiNodeCount)
  67. {
  68. routeMap.Remove(route);
  69. }
  70. }
  71. }
  72. }
  73. }