123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Documents;
- using XdCxRhDW.App.Model;
- using XdCxRhDW.Dto;
- using XdCxRhDW.Repostory;
- namespace XdCxRhDW.App
- {
- class ServerContext
- {
- public static ServerContext Instance { get; private set; } = new ServerContext();
- readonly List<ModelSvr> list = new List<ModelSvr>();
- public void Init()
- {
- Messenger.Defalut.Sub<SvrStateReportDto>("服务状态改变", dto =>
- {
- try
- {
- lock (this)
- {
- if (dto.ReportType == 0)
- {
- var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
- if (find == null)
- {
- list.Add(new ModelSvr()
- {
- SvrType = dto.SvrType,
- SvrID = dto.SvrID,
- BaseHttpAddr = dto.BaseHttpAddr,
- SwaggerAddr = dto.SwaggerAddr,
- ReportTime = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(SysConfig.Config.ZoneHours)),
- });
- }
- else
- {
- find.BaseHttpAddr = dto.BaseHttpAddr;
- find.SwaggerAddr = dto.SwaggerAddr;
- find.SvrType = dto.SvrType;
- find.SvrID = dto.SvrID;
- find.ReportTime = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(SysConfig.Config.ZoneHours));
- }
- }
- else
- {
- var find = list.Find(p => p.BaseHttpAddr == dto.BaseHttpAddr);
- if (find == null) return;
- list.Remove(find);
- }
- Messenger.Defalut.Pub("服务集合改变", list);
- }
- }
- catch (Exception ex)
- {
- XdCxRhDW.Framework.LogHelper.Error("处理服务状态上报异常", ex);
- }
- });
- CheckSvrState();
- }
- public List<ModelSvr> GetAll()
- {
- return list.Skip(0).ToList();
- }
- public List<ModelSvr> GetAll(EnumSvrType type)
- {
- lock (this)
- {
- return list.FindAll(p => p.SvrType == type);
- }
- }
- public ModelSvr GetOne(EnumSvrType type, string svrID)
- {
- lock (this)
- {
- return list.FirstOrDefault(p => p.SvrType == type && p.SvrID == svrID);
- }
- }
- public ModelSvr GetRandomOne(EnumSvrType type)
- {
- ModelSvr 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)
- {
- try
- {
- 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));
- }
- }
- catch (Exception ex)
- {
- XdCxRhDW.Framework.LogHelper.Error("服务状态检测异常", ex);
- }
- Thread.Sleep(10000);
- }
- });
- }
- }
- }
|