123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using Sers.Core.Module.Api.ApiDesc;
- using Sers.Core.Module.Api.RouteMap;
- using Sers.Core.Module.Rpc;
- using Sers.Gover.Base.Model;
- using Sers.ServiceCenter.Entity;
- namespace Sers.Gover.Base
- {
- /// <summary>
- /// 当前可调用的ApiService
- /// </summary>
- public class ApiLoadBalancingMng
- {
- public ApiLoadBalancingMng()
- {
- }
- protected readonly RouteMap<LoadBalancingForApiNode> routeMap = new RouteMap<LoadBalancingForApiNode>();
- public IEnumerable<SsApiDesc> GetAllApiDesc()
- {
- return routeMap.GetAll().Select((m) => m.apiDesc);
- }
- /// <summary>
- /// 通过负载均衡算法 获取可调用的ApiNode
- /// </summary>
- /// <param name="rpcData"></param>
- /// <param name="routeType"></param>
- /// <returns></returns>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public virtual ApiNode GetCurApiNodeByLoadBalancing(RpcContextData rpcData, out ERouteType routeType)
- {
- return routeMap.Routing(rpcData.route, out routeType)?.GetCurApiNodeBalancing();
- }
- [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
- protected virtual string GetApiRoute(ApiNode apiNode)
- {
- return apiNode.apiDesc.route;
- }
- public void ApiNode_Add(ApiNode apiNode)
- {
- lock (this)
- {
- var route = GetApiRoute(apiNode);
- if (string.IsNullOrWhiteSpace(route)) return;
- var lbApiNode = routeMap.Get(route);
- if (null == lbApiNode)
- {
- lbApiNode = new LoadBalancingForApiNode();
- routeMap.Set(route, lbApiNode);
- }
- lbApiNode.AddApiNode(apiNode);
- }
- }
- public void ApiNode_Remove(ApiNode apiNode)
- {
- lock (this)
- {
- var route = GetApiRoute(apiNode);
- if (string.IsNullOrWhiteSpace(route)) return;
- var lbApiNode = routeMap.Get(route);
- if (null == lbApiNode)
- {
- return;
- }
- lbApiNode.RemoveApiNode(apiNode);
- if (0 == lbApiNode.apiNodeCount)
- {
- routeMap.Remove(route);
- }
- }
- }
- }
- }
|