ApiLoadBalancingMng.cs 2.4 KB

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