RandomServers.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace AgileConfig.Client
  6. {
  7. public class RandomServers
  8. {
  9. private List<string> _serverUrls;
  10. private List<int> _serverIndexs;
  11. private int StartIndex = -1;
  12. public RandomServers(string serverUrls)
  13. {
  14. _serverUrls = new List<string>();
  15. _serverIndexs = new List<int>();
  16. if (!string.IsNullOrEmpty(serverUrls))
  17. {
  18. _serverUrls = serverUrls.Split(',').ToList();
  19. }
  20. else
  21. {
  22. throw new ArgumentNullException("serverUrls");
  23. }
  24. var randomIndex = new Random().Next(0, _serverUrls.Count);
  25. _serverIndexs.Add(randomIndex);
  26. int index = randomIndex + 1;
  27. while (true)
  28. {
  29. if (index == randomIndex)
  30. {
  31. break;
  32. }
  33. if (index >= _serverUrls.Count)
  34. {
  35. index = index - _serverUrls.Count;
  36. continue;
  37. }
  38. _serverIndexs.Add(index);
  39. index++;
  40. }
  41. }
  42. public int ServerCount
  43. {
  44. get
  45. {
  46. return _serverUrls.Count;
  47. }
  48. }
  49. private int NextIndex
  50. {
  51. get
  52. {
  53. if (IsComplete)
  54. {
  55. throw new Exception("No next index .");
  56. }
  57. StartIndex++;
  58. return StartIndex;
  59. }
  60. }
  61. public bool IsComplete
  62. {
  63. get
  64. {
  65. return StartIndex + 1 >= _serverIndexs.Count;
  66. }
  67. }
  68. public string Next()
  69. {
  70. return _serverUrls[_serverIndexs[NextIndex]];
  71. }
  72. }
  73. }