ServerContext.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using DW5S.DTO;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace DW5S.Service
  9. {
  10. public class ServerContext
  11. {
  12. public static ServerContext Instance { get; private set; } = new ServerContext();
  13. readonly List<SvrDto> list = new List<SvrDto>();
  14. public void Init()
  15. {
  16. Messenger.Defalut.Sub<SvrStateReportDto>("服务状态改变", dto =>
  17. {
  18. lock (this)
  19. {
  20. if (dto.ReportType == 0)
  21. {
  22. var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
  23. if (find == null)
  24. {
  25. list.Add(new SvrDto()
  26. {
  27. SvrType = dto.SvrType,
  28. SvrID = dto.SvrID,
  29. BaseHttpAddr = dto.BaseHttpAddr,
  30. SwaggerAddr = dto.SwaggerAddr,
  31. ReportTime = DateTimeOffset.UtcNow.ToLocalTime(),
  32. });
  33. }
  34. else
  35. {
  36. find.BaseHttpAddr = dto.BaseHttpAddr;
  37. find.SwaggerAddr = dto.SwaggerAddr;
  38. find.SvrType = dto.SvrType;
  39. find.SvrID = dto.SvrID;
  40. find.ReportTime = DateTimeOffset.UtcNow.ToLocalTime();
  41. }
  42. }
  43. else
  44. {
  45. var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
  46. if (find == null) return;
  47. list.Remove(find);
  48. }
  49. Messenger.Defalut.Pub("服务集合改变", list);
  50. }
  51. });
  52. CheckSvrState();
  53. }
  54. public List<SvrDto> GetAll()
  55. {
  56. return list.Skip(0).ToList();
  57. }
  58. public List<SvrDto> GetAll(EnumSvrType type)
  59. {
  60. lock (this)
  61. {
  62. return list.FindAll(p => p.SvrType == type);
  63. }
  64. }
  65. public SvrDto GetOne(EnumSvrType type, string svrID)
  66. {
  67. lock (this)
  68. {
  69. return list.FirstOrDefault(p => p.SvrType == type && p.SvrID == svrID);
  70. }
  71. }
  72. public SvrDto GetRandomOne(EnumSvrType type)
  73. {
  74. SvrDto svr = null;
  75. lock (this)
  76. {
  77. svr = list.Where(p => p.SvrType == type).OrderBy(p => Guid.NewGuid()).FirstOrDefault();
  78. }
  79. if (svr == null)
  80. throw new Exception($"找不到【{type.GetEnumDisplayName()}】");
  81. return svr;
  82. }
  83. private void CheckSvrState()
  84. {
  85. Task.Run(() =>
  86. {
  87. while (true)
  88. {
  89. lock (this)
  90. {
  91. List<string> tmp = new List<string>();
  92. list.ForEach(t =>
  93. {
  94. if ((DateTime.Now - t.ReportTime).TotalSeconds > 20)
  95. {
  96. tmp.Add(t.BaseHttpAddr);
  97. }
  98. });
  99. list.RemoveAll(p => tmp.Contains(p.BaseHttpAddr));
  100. }
  101. Thread.Sleep(10000);
  102. }
  103. });
  104. }
  105. }
  106. }