123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- using DW5S.DTO;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace DW5S.Service
- {
- public class ServerContext
- {
- public static ServerContext Instance { get; private set; } = new ServerContext();
- readonly List<SvrDto> list = new List<SvrDto>();
- public void Init()
- {
- Messenger.Defalut.Sub<SvrStateReportDto>("服务状态改变", dto =>
- {
- lock (this)
- {
- if (dto.ReportType == 0)
- {
- var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
- if (find == null)
- {
- list.Add(new SvrDto()
- {
- SvrType = dto.SvrType,
- SvrID = dto.SvrID,
- BaseHttpAddr = dto.BaseHttpAddr,
- SwaggerAddr = dto.SwaggerAddr,
- ReportTime = DateTimeOffset.UtcNow.ToLocalTime(),
- });
- }
- else
- {
- find.BaseHttpAddr = dto.BaseHttpAddr;
- find.SwaggerAddr = dto.SwaggerAddr;
- find.SvrType = dto.SvrType;
- find.SvrID = dto.SvrID;
- find.ReportTime = DateTimeOffset.UtcNow.ToLocalTime();
- }
- }
- else
- {
- var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
- if (find == null) return;
- list.Remove(find);
- }
- Messenger.Defalut.Pub("服务集合改变", list);
- }
- });
- CheckSvrState();
- }
- public List<SvrDto> GetAll()
- {
- return list.Skip(0).ToList();
- }
- public List<SvrDto> GetAll(EnumSvrType type)
- {
- lock (this)
- {
- return list.FindAll(p => p.SvrType == type);
- }
- }
- public SvrDto GetOne(EnumSvrType type, string svrID)
- {
- lock (this)
- {
- return list.FirstOrDefault(p => p.SvrType == type && p.SvrID == svrID);
- }
- }
- public SvrDto GetRandomOne(EnumSvrType type)
- {
- SvrDto svr = null;
- lock (this)
- {
- svr = list.Where(p => p.SvrType == type).OrderBy(p => Guid.NewGuid()).FirstOrDefault();
- }
- if (svr == null)
- throw new Exception($"找不到【{type.GetEnumDisplayName()}】");
- return svr;
- }
- private void CheckSvrState()
- {
- Task.Run(() =>
- {
- while (true)
- {
- lock (this)
- {
- List<string> tmp = new List<string>();
- list.ForEach(t =>
- {
- if ((DateTime.Now - t.ReportTime).TotalSeconds > 20)
- {
- tmp.Add(t.BaseHttpAddr);
- }
- });
- list.RemoveAll(p => tmp.Contains(p.BaseHttpAddr));
- }
- Thread.Sleep(10000);
- }
- });
- }
- }
- }
|