ApiLoadBalancingMng.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  36. protected virtual string GetApiRoute(ApiNode apiNode)
  37. {
  38. return apiNode.apiDesc.route;
  39. }
  40. public void ApiNode_Add(ApiNode apiNode)
  41. {
  42. lock (this)
  43. {
  44. var route = GetApiRoute(apiNode);
  45. if (string.IsNullOrWhiteSpace(route)) return;
  46. var lbApiNode = routeMap.Get(route);
  47. if (null == lbApiNode)
  48. {
  49. lbApiNode = new LoadBalancingForApiNode();
  50. routeMap.Set(route, lbApiNode);
  51. }
  52. lbApiNode.AddApiNode(apiNode);
  53. }
  54. }
  55. public void ApiNode_Remove(ApiNode apiNode)
  56. {
  57. lock (this)
  58. {
  59. var route = GetApiRoute(apiNode);
  60. if (string.IsNullOrWhiteSpace(route)) return;
  61. var lbApiNode = routeMap.Get(route);
  62. if (null == lbApiNode)
  63. {
  64. return;
  65. }
  66. lbApiNode.RemoveApiNode(apiNode);
  67. if (0 == lbApiNode.apiNodeCount)
  68. {
  69. routeMap.Remove(route);
  70. }
  71. }
  72. }
  73. }
  74. }