RoundLoadBalancer.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. using Grpc.Extension.Abstract;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Grpc.Extension.Client.LoadBalancer
  6. {
  7. /// <summary>
  8. /// 轮询负载
  9. /// </summary>
  10. public class RoundLoadBalancer : ILoadBalancer
  11. {
  12. private ConcurrentDictionary<string, int> _serviceInvokeIndexs = new ConcurrentDictionary<string, int>();
  13. /// <summary>
  14. /// 轮询获取Endpoint
  15. /// </summary>
  16. /// <param name="serviceName"></param>
  17. /// <param name="endpoints"></param>
  18. /// <returns></returns>
  19. public string SelectEndpoint(string serviceName, List<string> endpoints)
  20. {
  21. endpoints = endpoints.OrderBy(q => q).ToList();
  22. var index = _serviceInvokeIndexs.GetOrAdd(serviceName, 0);
  23. if (index >= endpoints.Count)
  24. {
  25. index = _serviceInvokeIndexs.AddOrUpdate(serviceName, 0, (k, v) => 0);
  26. }
  27. _serviceInvokeIndexs.AddOrUpdate(serviceName, index, (k, v) => v + 1);
  28. return endpoints.ElementAt(index);
  29. }
  30. }
  31. }