1修改测试问题;

2 增加redis表操作;
3 index文件监控处理;
master
mzhifa 7 months ago
parent ea5b04f32f
commit 966524013a

@ -0,0 +1,47 @@
using SqlSugar;
using System;
using System.Linq;
using System.Text;
namespace Txgy.RBS.DTO
{
///<summary>
///
///</summary>
public class RedisInfoDTO
{
public RedisInfoDTO()
{
}
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public int id { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string name { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string url { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public int port { get; set; }
}
}

@ -35,6 +35,12 @@ namespace Txgy.RBS.DTO
/// </summary> /// </summary>
public string otime { get; set; } public string otime { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public double? xlon { get; set; }
/// <summary> /// <summary>
/// Desc: /// Desc:
/// Default: /// Default:
@ -99,5 +105,6 @@ namespace Txgy.RBS.DTO
/// </summary> /// </summary>
public double? seismic_direction { get; set; } public double? seismic_direction { get; set; }
public string json_str { set; get; }
} }
} }

@ -1,6 +1,8 @@
using SqlSugar; using SqlSugar;
using System; using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Runtime.Serialization;
using System.Text; using System.Text;
namespace Txgy.RBS.DbModel.Models namespace Txgy.RBS.DbModel.Models
@ -182,7 +184,8 @@ namespace Txgy.RBS.DbModel.Models
public int push_wx_company_id { get; set; } public int push_wx_company_id { get; set; }
[Navigate(NavigateType.OneToOne, nameof(project_id))] [Navigate(NavigateType.OneToOne, nameof(project_id))]
public station_file stationFile { get; set; } // [SugarColumn(IsIgnore = true)]
public station_file station_file { get; set; }
[Navigate(NavigateType.OneToOne, nameof(project_id))] [Navigate(NavigateType.OneToOne, nameof(project_id))]

@ -0,0 +1,48 @@
using SqlSugar;
using System;
using System.Linq;
using System.Text;
namespace Txgy.RBS.DbModel.Models
{
///<summary>
///
///</summary>
public class redis_server
{
public redis_server()
{
}
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(IsPrimaryKey = true,IsIdentity =true)]
public int id { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string name { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public string url { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:True
/// </summary>
public int port { get; set; }
}
}

@ -15,7 +15,7 @@ namespace Txgy.RBS.DbModel.Models
/// Default: /// Default:
/// Nullable:True /// Nullable:True
/// </summary> /// </summary>
[SugarColumn(IsPrimaryKey = true,IsIdentity =true)] [SugarColumn(IsPrimaryKey = true)]
public int id { get; set; } public int id { get; set; }
/// <summary> /// <summary>

@ -8,7 +8,7 @@ namespace Txgy.RBS.DbModel.Models
///<summary> ///<summary>
/// ///
///</summary> ///</summary>
public partial class time_tab public class time_tab
{ {
public time_tab() public time_tab()
{ {
@ -20,7 +20,7 @@ namespace Txgy.RBS.DbModel.Models
/// Default: /// Default:
/// Nullable:True /// Nullable:True
/// </summary> /// </summary>
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] [SugarColumn(IsPrimaryKey = true)]
public int id { get; set; } public int id { get; set; }
/// <summary> /// <summary>
@ -28,7 +28,7 @@ namespace Txgy.RBS.DbModel.Models
/// Default: /// Default:
/// Nullable:True /// Nullable:True
/// </summary> /// </summary>
public int? project_id { get; set; } public int project_id { get; set; }
/// <summary> /// <summary>
/// Desc: /// Desc:

@ -10,9 +10,13 @@ namespace Txgy.RBS.Framework
public class CommonData public class CommonData
{ {
public static string BaseProjectPath { get; set; } = "d:\\Project"; public static string BaseProjectPath { get; set; } = "d:\\Project";
public static string RedisDefaultPath { get; set; } = "program\\server";
public static string ApmsDefaultPath { get; set; } = "program\\apms\\gw.apms.json"; public static string ApmsDefaultPath { get; set; } = "program\\apms\\gw.apms.json";
public static string RecvDefaultPath { get; set; } = "program\\recvmqtt\\gw.recvmqtt.json"; public static string RecvDefaultPath { get; set; } = "program\\recvmqtt\\gw.recvmqtt.json";
public static string RedisPublish { get; set; } = "server_status";
/// <summary>//From:www.13le.com /// <summary>//From:www.13le.com
/// 复制文件夹下所有文件 /// 复制文件夹下所有文件

@ -0,0 +1,155 @@
using ServiceStack.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using Txgy.RBS.Framework.Models;
namespace Txgy.RBS.Framework.FileWatcherHelper
{
public class FilesWatcherService
{
public FilesWatcherService(int proId, string projectName, string path)
{
projectId = proId;
proName = projectName;
watcherPath = path;
// string filter = "*.txt";
// WatcherPath = AppDomain.CurrentDomain.BaseDirectory;
// InitializeParams(filter, watcherPath);
}
private string watcherPath;
public string WatcherPath
{
get { return watcherPath; }
}
private string proName;
public string ProName
{
get { return proName; }
}
private int projectId;
public int ProjectId
{
get { return projectId; }
}
public DateTime StartTime { get; set; }
public void Start()
{
WatchStartOrSopt(true);
StartTime = DateTime.Now;
}
public void Stop()
{
WatchStartOrSopt(false);
}
public Action<MsEventModel, FileSystemEventArgs> WatcherFileChanged;
public void InitializeParams(string fileFilter="*.index")
{
//如果设置的目录不存在设置到根目录
if (!File.Exists(watcherPath))
{
Directory.CreateDirectory(watcherPath);
// watcherPath = AppDomain.CurrentDomain.BaseDirectory;
}
watcher = new FileSystemWatcher();
//初始化监听
watcher.BeginInit();
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//设置监听的路径
watcher.Path = watcherPath;
watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
// watcher.Created += Watcher_Created;
watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
watcher.Error += OnError;
//设置监听文件类型
watcher.Filter = fileFilter;
//设置是否监听子目录
watcher.IncludeSubdirectories = false;
//设置是否启用监听
watcher.EnableRaisingEvents = false;
watcher.EndInit();
}
private void OnError(object sender, ErrorEventArgs e)
{
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
Thread.Sleep(100);
// string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
watcher.EnableRaisingEvents = false;
Debug.WriteLine($"最后修改时间:{lastWriteTime}");
string lastLine = File.ReadLines(e.FullPath).Last().Trim();
var msEvent = new MsEventModel(lastLine) { CurrentTime = DateTime.Now };
msEvent.ProjectId = this.ProjectId;
msEvent.ProjectName = this.ProName;
WatcherFileChanged?.Invoke(msEvent, e);
watcher.EnableRaisingEvents = true;
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
DateTime dt = DateTime.Now;
string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
tmp += "改变类型 :" + e.ChangeType.ToString() + "\r\n"; ;
tmp += "文件全称:" + e.FullPath + "\r\n";
}
/// <summary>
/// 启动或者停止监听
/// </summary>
/// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
private void WatchStartOrSopt(bool IsEnableRaising)
{
watcher.EnableRaisingEvents = IsEnableRaising;
}
private FileSystemWatcher watcher = new FileSystemWatcher();
}
}

@ -5,7 +5,8 @@ namespace Txgy.RBS.Framework.Models
{ {
public class MsEventModel public class MsEventModel
{ {
public int ID { get; set; } public int ProjectId { get; set; }
public string ProjectName { get; set; }
public DateTime CurrentTime { get; set; } public DateTime CurrentTime { get; set; }
public DateTime OriginTime { get; set; } public DateTime OriginTime { get; set; }
public double EastCoordinate { get; set; } public double EastCoordinate { get; set; }
@ -14,7 +15,8 @@ namespace Txgy.RBS.Framework.Models
public double ML { get; set; } public double ML { get; set; }
public double Energy { get; set; } public double Energy { get; set; }
public int PhasesCount { get; set; }
public int AmpsCount { get; set; }
public int EarthquakeSource { get; set; } public int EarthquakeSource { get; set; }
public bool IsSend { get => isSend; set => isSend = value; } public bool IsSend { get => isSend; set => isSend = value; }

@ -2,7 +2,9 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks; using System.Threading.Tasks;
using Txgy.RBS.Framework.FileWatcherHelper;
namespace Txgy.RBS.Framework namespace Txgy.RBS.Framework
{ {
@ -11,7 +13,7 @@ namespace Txgy.RBS.Framework
/// <summary> /// <summary>
/// server程序 /// server程序
/// </summary> /// </summary>
public ProcessInfo Server { get; set; } // public ProcessInfo Server { get; set; }
/// <summary> /// <summary>
/// Recv程序 /// Recv程序
/// </summary> /// </summary>
@ -21,5 +23,9 @@ namespace Txgy.RBS.Framework
/// </summary> /// </summary>
public ProcessInfo Apms { get; set; } public ProcessInfo Apms { get; set; }
[JsonIgnore]
public FilesWatcherService FilesWatcherService { get; set; }
} }
} }

@ -38,6 +38,7 @@ namespace Txgy.RBS.Framework.RedisHelper.Init
MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize, MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize,
MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize, MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize,
AutoStart = RedisConfigInfo.AutoStart, AutoStart = RedisConfigInfo.AutoStart,
DefaultDb=2
}); });
} }

@ -14,13 +14,14 @@ namespace Txgy.RBS.IServices
CreateMap<result, ResultDTO>().ReverseMap(); CreateMap<result, ResultDTO>().ReverseMap();
CreateMap<project_info, ProjectInfoDTO>() CreateMap<project_info, ProjectInfoDTO>()
.ForMember(p => p.timeTab, pd => pd.MapFrom(s => s.time_tab)) .ForMember(p => p.timeTab, pd => pd.MapFrom(s => s.time_tab))
.ForMember(p => p.stationFile, pd => pd.MapFrom(s => s.stationFile)).ReverseMap(); .ForMember(p => p.stationFile, pd => pd.MapFrom(s => s.station_file)).ReverseMap();
CreateMap<project_used,ProjectUsedDTO>().ReverseMap(); CreateMap<project_used,ProjectUsedDTO>().ReverseMap();
CreateMap<station, StationDTO>().ReverseMap(); CreateMap<station, StationDTO>().ReverseMap();
CreateMap<station_file, StationFileDTO>().ReverseMap(); CreateMap<station_file, StationFileDTO>().ReverseMap();
CreateMap<station_num_vpn,StationNumVpnDTO>().ReverseMap(); CreateMap<station_num_vpn,StationNumVpnDTO>().ReverseMap();
CreateMap<time_tab, TimeTabDTO>().ReverseMap(); CreateMap<time_tab, TimeTabDTO>().ReverseMap();
CreateMap<global_config,GlobalConfigDTO>().ReverseMap(); CreateMap<global_config,GlobalConfigDTO>().ReverseMap();
CreateMap<redis_server, RedisInfoDTO>().ReverseMap();
} }
} }
} }

@ -20,7 +20,19 @@ namespace Txgy.RBS.IServices
ResultDTO GetResultInfo(int id); ResultDTO GetResultInfo(int id);
List<ResultDTO> GetResultInfo(string projectName, DateTime startTime,DateTime endTime);
List<ResultDTO> GetAllResultInfo(); List<ResultDTO> GetAllResultInfo();
List<RedisInfoDTO> GetAllRidesInfo();
ApiResult AddRedisInfo(RedisInfoDTO redisServerDTO);
ApiResult DeleteRedisInfo(int id);
ApiResult UpdateRedisInfo(RedisInfoDTO redisServerDTO);
RedisInfoDTO GetRedisInfo(int id);
} }
} }

@ -32,6 +32,12 @@ namespace Txgy.RBS.Server.WebApi.Controllers
[HttpPost] [HttpPost]
public ApiResult AddProjectInfo(ProjectInfoDTO project) public ApiResult AddProjectInfo(ProjectInfoDTO project)
{ {
//var pro= _projectInfoService.GetProjectInfo(1);
// pro.id=project.id;
// pro.project_id = project.project_id;
// pro.project_name = project.project_name;
// pro.moni_layer = project.moni_layer;
// pro.moni_num = project.moni_num;
return _projectInfoService.AddProjectInfo(project); return _projectInfoService.AddProjectInfo(project);
} }
@ -144,7 +150,7 @@ namespace Txgy.RBS.Server.WebApi.Controllers
System.IO.File.WriteAllText(Path.Combine(path, CommonData.RecvDefaultPath), recvJson); System.IO.File.WriteAllText(Path.Combine(path, CommonData.RecvDefaultPath), recvJson);
_processConfig.RecvMqtt.ProPath = Path.Combine(path, _processConfig.RecvMqtt.ProPath); _processConfig.RecvMqtt.ProPath = Path.Combine(path, _processConfig.RecvMqtt.ProPath);
} }
_processConfig.Server.ProPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _processConfig.Server.ProPath); _processConfig.FilesWatcherService = new Framework.FileWatcherHelper.FilesWatcherService(curProject.project_id,curProject.project_name,apm.savepath);
res= _projectInfoService.StartProject(curProject.project_name, _processConfig); res= _projectInfoService.StartProject(curProject.project_name, _processConfig);
res.Data = curProject; res.Data = curProject;
} }

@ -19,7 +19,7 @@ namespace Txgy.RBS.Server.WebApi.Controllers
this._resultInfoService = resultInfoService; this._resultInfoService = resultInfoService;
} }
[HttpPost] [HttpPost]
public ApiResult AddProjectInfo(ResultDTO resultDTO) public ApiResult AddResultInfo(ResultDTO resultDTO)
{ {
return _resultInfoService.AddResultInfo(resultDTO); return _resultInfoService.AddResultInfo(resultDTO);
} }
@ -41,11 +41,40 @@ namespace Txgy.RBS.Server.WebApi.Controllers
{ {
return _resultInfoService.GetResultInfo(id); return _resultInfoService.GetResultInfo(id);
} }
[HttpGet]
public List <ResultDTO> GetResultInfo(string projectName, DateTime startTime, DateTime endTime)
{
return _resultInfoService.GetResultInfo(projectName.Trim(), startTime, endTime);
}
[HttpGet] [HttpGet]
public List<ResultDTO> GetAllResultInfo() public List<ResultDTO> GetAllResultInfo()
{ {
return _resultInfoService.GetAllResultInfo(); return _resultInfoService.GetAllResultInfo();
} }
[HttpPost]
public ApiResult AddRedisInfo(RedisInfoDTO redisDTO)
{
return _resultInfoService.AddRedisInfo(redisDTO);
}
[HttpDelete("{id}")]
public ApiResult DeleteRedisInfo(int id)
{
return _resultInfoService.DeleteRedisInfo(id);
}
[HttpPost]
public ApiResult UpdateRedisInfo(RedisInfoDTO redisDTO)
{
return _resultInfoService.UpdateRedisInfo(redisDTO);
}
[HttpGet]
public List<RedisInfoDTO> GetAllRedisInfo()
{
return _resultInfoService.GetAllRidesInfo();
}
} }
} }

@ -7,9 +7,6 @@ using Txgy.RBS.Server.WebApi.Register;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Register(); //业务逻辑层的注册
//支持Automapper映射 //支持Automapper映射
builder.Services.AddAutoMapper(typeof(AutoMapObject)); builder.Services.AddAutoMapper(typeof(AutoMapObject));
@ -19,6 +16,10 @@ builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
// 启用本地缓存 // 启用本地缓存
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
//业务逻辑层的注册
builder.Register();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

@ -3,8 +3,10 @@ using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using SqlSugar; using SqlSugar;
using System.Diagnostics;
using System.Reflection; using System.Reflection;
using Txgy.RBS.Framework; using Txgy.RBS.Framework;
using Txgy.RBS.Framework.RedisHelper.Init;
using Txgy.RBS.Framework.RedisHelper.Service; using Txgy.RBS.Framework.RedisHelper.Service;
using Txgy.RBS.Services; using Txgy.RBS.Services;
@ -14,7 +16,6 @@ namespace Txgy.RBS.Server.WebApi.Register
{ {
public static void Register(this WebApplicationBuilder applicationBuilder) public static void Register(this WebApplicationBuilder applicationBuilder)
{ {
//替换容器Autofac //替换容器Autofac
applicationBuilder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); applicationBuilder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
applicationBuilder.Host.ConfigureContainer<ContainerBuilder>(ConfigurationBinder => applicationBuilder.Host.ConfigureContainer<ContainerBuilder>(ConfigurationBinder =>
@ -26,7 +27,7 @@ namespace Txgy.RBS.Server.WebApi.Register
Assembly serviceAssembly = Assembly.Load("Txgy.RBS.IServices"); Assembly serviceAssembly = Assembly.Load("Txgy.RBS.IServices");
ConfigurationBinder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces(); ConfigurationBinder.RegisterAssemblyTypes(interfaceAssembly, serviceAssembly).AsImplementedInterfaces();
#endregion #endregion
var pro= applicationBuilder.Configuration.GetSection("process").Get<ProcessConfig>(); var pro = applicationBuilder.Configuration.GetSection("process").Get<ProcessConfig>();
ConfigurationBinder.RegisterType<ProcessManagerService>().SingleInstance(); ConfigurationBinder.RegisterType<ProcessManagerService>().SingleInstance();
#region 注册每个控制器和抽象之间的关系 #region 注册每个控制器和抽象之间的关系
var controllerBaseType = typeof(ControllerBase); var controllerBaseType = typeof(ControllerBase);
@ -68,11 +69,40 @@ namespace Txgy.RBS.Server.WebApi.Register
ConfigurationBinder.RegisterType<RedisSetService>(); ConfigurationBinder.RegisterType<RedisSetService>();
ConfigurationBinder.RegisterType<RedisStringService>(); ConfigurationBinder.RegisterType<RedisStringService>();
ConfigurationBinder.RegisterType<RedisZSetService>(); ConfigurationBinder.RegisterType<RedisZSetService>();
//启动redis服务
{
//* Create your Process
Process process = new Process();
process.Exited += Process_Exited;
process.EnableRaisingEvents = true;
process.StartInfo.FileName = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonData.RedisDefaultPath, "server.exe"));
process.StartInfo.WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CommonData.RedisDefaultPath);
// process.StartInfo.Arguments = "service.conf";
Debug.WriteLine($"*******ProcessName:{process.StartInfo.FileName}, arguments:{process.StartInfo.Arguments}*********");
process.StartInfo.UseShellExecute = true;
process.StartInfo.CreateNoWindow = false;
//* Start process and handlers
Process[] localByName = Process.GetProcessesByName("server");
if (localByName.Length != 0)
{
localByName[0].Exited += Process_Exited;
localByName[0].EnableRaisingEvents = true;
process = localByName[0];
return;
}
bool res = process.Start();
} }
#endregion
}
#endregion
}); });
applicationBuilder.Services.Configure<RedisConfigInfo>(applicationBuilder.Configuration.GetSection("RedisConfigInfo"));
}
private static void Process_Exited(object? sender, EventArgs e)
{
} }
} }
} }

@ -22,7 +22,7 @@
<ItemGroup> <ItemGroup>
<None Update="rbs_server_db.db"> <None Update="rbs_server_db.db">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>

@ -46,5 +46,15 @@
"ShowState": 0 "ShowState": 0
} }
}, },
"RedisConfigInfo": {
"WriteServerList": "127.0.0.1:6379",
"ReadServerList": "127.0.0.1:6379",
"MaxWritePoolSize": 60,
"MaxReadPoolSize": 60,
"LocalCacheTime": 180,
"AutoStart": true,
"RecordeLog": true
},
"AllowedHosts": "*" "AllowedHosts": "*"
} }

@ -1,35 +1,52 @@
using System.Diagnostics; using Aspose.Cells;
using Txgy.RBS.Framework.Api;
using Txgy.RBS.Framework;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using ServiceStack;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.Data; using System.Data;
using System.Diagnostics;
using Txgy.RBS.DTO; using Txgy.RBS.DTO;
using Aspose.Cells; using Txgy.RBS.Framework;
using Txgy.RBS.Framework.Api;
using Txgy.RBS.Framework.FileWatcherHelper;
using Txgy.RBS.Framework.Models; using Txgy.RBS.Framework.Models;
using Txgy.RBS.Framework.RedisHelper.Service;
using Txgy.RBS.IServices;
namespace Txgy.RBS.Services namespace Txgy.RBS.Services
{ {
public class ProcessManagerService public class ProcessManagerService
{ {
private readonly IMemoryCache _cache; private readonly IMemoryCache _cache;
private readonly RedisListService _redisList;
private readonly IResultInfoService _resultInfoService;
public ProcessManagerService( IMemoryCache cache) public ProcessManagerService(RedisListService redisList, IResultInfoService resultInfoService, IMemoryCache cache)
{ {
_cache = cache;
MoniTimer.Interval = 10000; MoniTimer.Interval = 10000;
MoniTimer.Elapsed += MoniTimer_Elapsed; MoniTimer.Elapsed += MoniTimer_Elapsed;
MoniTimer.Start(); MoniTimer.Start();
this._redisList = redisList;
this._resultInfoService = resultInfoService;
_cache = cache;
RedisServer = new ProcessInfo()
{
ProName = "server",
StartTime = DateTime.Now,
State = true
};
} }
public ProcessInfo RedisServer { get; set; }
private void MoniTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) private void MoniTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{ {
foreach (var item in ProjectMonitor) foreach (var item in ProjectMonitor)
{ {
_redisList.Publish(CommonData.RedisPublish, Newtonsoft.Json.JsonConvert.SerializeObject(new
{
projectName = item.Key,
ProName = RedisServer.ProName,
RunState = RedisServer.State?1:0,
RunTime = (DateTime.Now - RedisServer.StartTime).TotalSeconds,
}));
foreach (var proValue in item.Value.GetType().GetProperties()) foreach (var proValue in item.Value.GetType().GetProperties())
{ {
var pro = proValue.GetValue(item.Value) as ProcessInfo; var pro = proValue.GetValue(item.Value) as ProcessInfo;
@ -38,10 +55,22 @@ namespace Txgy.RBS.Services
int sfp = FindProcess(pro); int sfp = FindProcess(pro);
if (sfp != 0) if (sfp != 0)
{ {
Console.WriteLine($"{pro.ProName}程序重启中,path:{pro.ProPath}"); pro.State = false;
Console.WriteLine($"{pro.ProName}程序重启中, path:{pro.ProPath}");
StartProcess(pro); StartProcess(pro);
Thread.Sleep(20); Thread.Sleep(20);
} }
else
{
pro.State = true;
}
_redisList.Publish(CommonData.RedisPublish, Newtonsoft.Json.JsonConvert.SerializeObject(new
{
projectName=item.Key,
ProName = pro.ProName,
RunState = sfp == 0 ? 1 : 0,
RunTime = (DateTime.Now - pro.StartTime).TotalSeconds,
}));
} }
} }
} }
@ -54,6 +83,9 @@ namespace Txgy.RBS.Services
if (!ProjectMonitor.ContainsKey(projectName)) if (!ProjectMonitor.ContainsKey(projectName))
{ {
ProjectMonitor.TryAdd(projectName, processInfo); ProjectMonitor.TryAdd(projectName, processInfo);
processInfo.FilesWatcherService.InitializeParams();
processInfo.FilesWatcherService.Start();
processInfo.FilesWatcherService.WatcherFileChanged = WatcherChanged;
} }
} }
System.Timers.Timer MoniTimer { get; set; } = new System.Timers.Timer(); System.Timers.Timer MoniTimer { get; set; } = new System.Timers.Timer();
@ -61,16 +93,60 @@ namespace Txgy.RBS.Services
{ {
if (ProjectMonitor.ContainsKey(projectName)) if (ProjectMonitor.ContainsKey(projectName))
{ {
ProjectMonitor.TryRemove(projectName, out ProcessConfig pro); ProjectMonitor.TryRemove(projectName, out ProcessConfig process);
process.FilesWatcherService.Stop();
foreach (var proValue in process.GetType().GetProperties())
{
var pro = proValue.GetValue(process) as ProcessInfo;
if (pro != null)
{
_redisList.Publish(CommonData.RedisPublish, Newtonsoft.Json.JsonConvert.SerializeObject(new
{
projectName = projectName,
ProName = pro.ProName,
RunState = 0,
RunTime = (DateTime.Now - pro.StartTime).TotalSeconds,
}));
} }
} }
}
}
void WatcherChanged(MsEventModel msEvent, FileSystemEventArgs e)
{
_resultInfoService.AddResultInfo(new ResultDTO
{
project_id = msEvent.ProjectId,
otime = msEvent.OriginTime.ToString("O"),
xlon = msEvent.EastCoordinate,
ylat = msEvent.NorthCoordinate,
depth = msEvent.Depth,
ml = msEvent.ML,
energy = msEvent.Energy,
// rms=msEvent.
phases_count = msEvent.PhasesCount,
amps_count = msEvent.AmpsCount,
});
_redisList.Publish($"{msEvent.ProjectName}result", Newtonsoft.Json.JsonConvert.SerializeObject(new
{
projectName = msEvent.ProjectName,
ProName = msEvent.OriginTime,
message = msEvent.ToString(),
jsonStr = ""
}));
}
#region 方法 #region 方法
public ApiResult StartProject(string projectName, ProcessConfig processConfig) public ApiResult StartProject(string projectName, ProcessConfig processConfig)
{ {
int res = 0; int res = 0;
if (ProjectMonitor.ContainsKey(projectName)) new ApiResult(); if (ProjectMonitor.ContainsKey(projectName))
{
return new ApiResult();
}
foreach (var item in processConfig.GetType().GetProperties()) foreach (var item in processConfig.GetType().GetProperties())
{ {
var pro = item.GetValue(processConfig) as ProcessInfo; var pro = item.GetValue(processConfig) as ProcessInfo;
@ -79,11 +155,11 @@ namespace Txgy.RBS.Services
res = StartProcess(pro); res = StartProcess(pro);
if (res != 0) if (res != 0)
{ {
break; continue;
} }
pro.StartTime = DateTime.Now; pro.StartTime = DateTime.Now;
pro.State = true; pro.State = true;
_cache.Set(pro.ProPath, pro); // _cache.Set(pro.ProPath, pro);
Thread.Sleep(10); Thread.Sleep(10);
} }
} }
@ -113,7 +189,7 @@ namespace Txgy.RBS.Services
break; break;
} }
pro.State = false; pro.State = false;
_cache.Set(pro.ProPath, pro); // _cache.Set(pro.ProPath, pro);
Thread.Sleep(10); Thread.Sleep(10);
} }
} }
@ -246,7 +322,15 @@ namespace Txgy.RBS.Services
} }
else else
{ {
var pro= localByName.Where(p => p.MainModule.FileName.Contains(processInfo.ProPath)); List<Process> pro = null;
if (processInfo.ProName == "server")
{
pro = localByName.Where(p => p.MainModule.FileName.Contains(processInfo.ProName)).ToList();
}
else
{
pro = localByName.Where(p => p.MainModule.FileName.Contains(processInfo.ProPath)).ToList();
}
if (!pro.Any()) if (!pro.Any())
{ {
ri = 1; ri = 1;
@ -265,9 +349,14 @@ namespace Txgy.RBS.Services
public ApiResult GetState(string projectName, int id) public ApiResult GetState(string projectName, int id)
{ {
ProcessInfo pro = null;
if(id==1)
{
pro = this.RedisServer;
}
ProjectMonitor.TryGetValue(projectName, out ProcessConfig process); ProjectMonitor.TryGetValue(projectName, out ProcessConfig process);
if (process == null|| (id<1 || id>3)) { return new ApiResult(); } if (process == null || (id < 1|| id > 3)) { return new ApiResult(); }
ProcessInfo pro = id == 1 ? process.Server : id == 2 ? process.Apms : process.RecvMqtt; pro = id == 1 ?pro:(id==2)? process.Apms : process.RecvMqtt;
int sfp = FindProcess(pro); int sfp = FindProcess(pro);
if (sfp != 0) if (sfp != 0)
{ {
@ -275,12 +364,13 @@ namespace Txgy.RBS.Services
} }
return new ApiResult return new ApiResult
{ {
Code = System.Net.HttpStatusCode.OK, Data = new Code = System.Net.HttpStatusCode.OK,
Data = new
{ {
name=pro.ProName, name = pro.ProName,
state= sfp == 0 ? 1 : 0, state = sfp == 0 ? 1 : 0,
start_time=pro.StartTime, start_time = pro.StartTime,
running_time=(DateTime.Now-pro.StartTime).TotalSeconds, running_time = (DateTime.Now - pro.StartTime).TotalSeconds,
} }
}; };
} }

@ -1,4 +1,5 @@
using AutoMapper; using Aspose.Cells;
using AutoMapper;
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Memory;
using SqlSugar; using SqlSugar;
using System; using System;
@ -29,20 +30,31 @@ namespace Txgy.RBS.Services
public ApiResult AddProjectInfo(ProjectInfoDTO project) public ApiResult AddProjectInfo(ProjectInfoDTO project)
{ {
project_info project_Info = _iMapper.Map<project_info>(project); try
{
var pro = _Client.InsertNav(project_Info).Include(p=>p.stationFile).ThenInclude(t=>t.stations) _Client.Ado.BeginTran();
var projectInfo = _iMapper.Map<project_info>(project);
//project_id要手动赋值
projectInfo.project_id= _Client.Queryable<project_info>().Max(p=>p.project_id)+1;
projectInfo.station_file.project_id= projectInfo.project_id;
projectInfo.time_tab.project_id = projectInfo.project_id;
var pro = _Client.InsertNav(projectInfo).Include(p => p.station_file).ThenInclude(t => t.stations)
.Include(time => time.time_tab).ExecuteCommand(); .Include(time => time.time_tab).ExecuteCommand();
if (pro)
_Client.Ado.CommitTran();
}
catch (Exception ex)
{ {
return new ApiResult(); _Client.Ado.RollbackTran();
return new ApiResult() { Message = $"添加失败,{ex}" };
} }
return new ApiResult() { Message = "添加失败" }; return new ApiResult();
} }
public ApiResult DeleteProjectInfo(int id) public ApiResult DeleteProjectInfo(int id)
{ {
var res = _Client.DeleteNav<project_info>(p => p.id == id).Include(p => p.stationFile).ThenInclude(t => t.stations) var res = _Client.DeleteNav<project_info>(p => p.id == id).Include(p => p.station_file).ThenInclude(t => t.stations)
.Include(time => time.time_tab).ExecuteCommand(); .Include(time => time.time_tab).ExecuteCommand();
if (res) if (res)
{ {
@ -53,7 +65,7 @@ namespace Txgy.RBS.Services
public List<ProjectInfoDTO> GetAllProjectInfo() public List<ProjectInfoDTO> GetAllProjectInfo()
{ {
var projects = _Client.Queryable<project_info>().Includes(x => x.stationFile, t=>t.stations) var projects = _Client.Queryable<project_info>().Includes(x => x.station_file, t=>t.stations)
.Includes(ti=>ti.time_tab).ToList(); .Includes(ti=>ti.time_tab).ToList();
var projectDTOs= _iMapper.Map<List<ProjectInfoDTO>>(projects); var projectDTOs= _iMapper.Map<List<ProjectInfoDTO>>(projects);
return projectDTOs; return projectDTOs;
@ -69,7 +81,7 @@ namespace Txgy.RBS.Services
public ApiResult UpdateProjectInfo(ProjectInfoDTO project) public ApiResult UpdateProjectInfo(ProjectInfoDTO project)
{ {
project_info projectInfo = _iMapper.Map<project_info>(project); project_info projectInfo = _iMapper.Map<project_info>(project);
var res = _Client.UpdateNav(projectInfo).Include(p => p.stationFile).ThenInclude(t => t.stations) var res = _Client.UpdateNav(projectInfo).Include(p => p.station_file).ThenInclude(t => t.stations)
.Include(time => time.time_tab).ExecuteCommand(); .Include(time => time.time_tab).ExecuteCommand();
if (res) if (res)
{ {
@ -80,19 +92,8 @@ namespace Txgy.RBS.Services
public ProjectInfoDTO GetProjectInfo(int id) public ProjectInfoDTO GetProjectInfo(int id)
{ {
project_info projectInfo = _Client.Queryable<project_info>().Includes(x => x.stationFile, t => t.stations).Includes(ti => ti.time_tab).Where(p => p.id == id).First(); var projectInfo = _Client.Queryable<project_info>().Where(p => p.project_id == id).Includes(p=>p.station_file, s=>s.stations).Includes(p=>p.time_tab).ToList();
ProjectInfoDTO projectInfoDTO = _iMapper.Map<project_info, ProjectInfoDTO>(projectInfo); ProjectInfoDTO projectInfoDTO = _iMapper.Map<project_info, ProjectInfoDTO>(projectInfo[0]);
//test
//if (projectInfoDTO != null)
//{
// projectInfoDTO.id = 6;
// projectInfoDTO.project_id = 9;
// projectInfoDTO.project_name = "tea";
// projectInfoDTO.moni_layer = 1;
// projectInfoDTO.moni_num = 8;
// var a = UpdateProjectInfo(projectInfoDTO);
//}
return projectInfoDTO; return projectInfoDTO;
} }
@ -120,7 +121,6 @@ namespace Txgy.RBS.Services
} }
public ApiResult GetState(string projectName, int id) public ApiResult GetState(string projectName, int id)
{ {
return _processManager.GetState(projectName, id); return _processManager.GetState(projectName, id);
} }

@ -21,6 +21,19 @@ namespace Txgy.RBS.Services
this._iMapper = iMapper; this._iMapper = iMapper;
} }
public ApiResult AddRedisInfo(RedisInfoDTO redisServerDTO)
{
int res = 0;
var redisServer = _iMapper.Map<redis_server>(redisServerDTO);
res = _Client.Insertable(redisServer).ExecuteCommand();
if (res > 0)
{
return new ApiResult();
}
return new ApiResult() { Message = "添加失败" };
}
public ApiResult AddResultInfo(ResultDTO resultJsonDTO) public ApiResult AddResultInfo(ResultDTO resultJsonDTO)
{ {
int res = 0; int res = 0;
@ -34,6 +47,16 @@ namespace Txgy.RBS.Services
return new ApiResult() { Message = "添加失败" }; return new ApiResult() { Message = "添加失败" };
} }
public ApiResult DeleteRedisInfo(int id)
{
int res = _Client.Deleteable<redis_server>(p => p.id == id).ExecuteCommand();
if (res > 0)
{
return new ApiResult();
}
return new ApiResult() { Message = "删除失败" };
}
public ApiResult DeleteResultInfo(int id) public ApiResult DeleteResultInfo(int id)
{ {
int res= _Client.Deleteable<result>(p=>p.id==id).ExecuteCommand(); int res= _Client.Deleteable<result>(p=>p.id==id).ExecuteCommand();
@ -49,7 +72,18 @@ namespace Txgy.RBS.Services
var projects = _Client.Queryable<result>().ToList(); var projects = _Client.Queryable<result>().ToList();
return _iMapper.Map<List<ResultDTO>>(projects); return _iMapper.Map<List<ResultDTO>>(projects);
} }
public List<RedisInfoDTO> GetAllRidesInfo()
{
var projects = _Client.Queryable<redis_server>().ToList();
return _iMapper.Map<List<RedisInfoDTO>>(projects);
}
public RedisInfoDTO GetRedisInfo(int id)
{
var RedisServer = _Client.Queryable<redis_server>().First(c => c.id == id);
var redisServerDTO = _iMapper.Map<RedisInfoDTO>(RedisServer);
return redisServerDTO;
}
public ResultDTO GetResultInfo(int id) public ResultDTO GetResultInfo(int id)
{ {
@ -58,6 +92,29 @@ namespace Txgy.RBS.Services
return resultJsonDTO; return resultJsonDTO;
} }
public List<ResultDTO> GetResultInfo(string projectName, DateTime startTime, DateTime endTime)
{
var pro= _Client.Queryable<project_info>().Where(p => p.project_name == projectName).First();
if (pro == null)
{
return new List<ResultDTO>();
}
var results= _Client.Queryable<result>().Where(r => r.project_id == pro.project_id
&& (startTime < Convert.ToDateTime(r.otime) && Convert.ToDateTime(r.otime) < endTime)).ToList();
return _iMapper.Map<List<ResultDTO>>(results);
}
public ApiResult UpdateRedisInfo(RedisInfoDTO redisServerDTO)
{
var redisServer = _iMapper.Map<redis_server>(redisServerDTO);
int res = _Client.Updateable(redisServer).ExecuteCommand();
if (res > 0)
{
return new ApiResult();
}
return new ApiResult() { Message = "更新失败" };
}
public ApiResult UpdateResultInfo(ResultDTO resultJsonDTO) public ApiResult UpdateResultInfo(ResultDTO resultJsonDTO)
{ {
result result_Json = _iMapper.Map<result> (resultJsonDTO); result result_Json = _iMapper.Map<result> (resultJsonDTO);

@ -66,3 +66,35 @@
[37440] 17 Apr 14:21:54.835 * Running mode=standalone, port=6379. [37440] 17 Apr 14:21:54.835 * Running mode=standalone, port=6379.
[37440] 17 Apr 14:21:54.835 # Server initialized [37440] 17 Apr 14:21:54.835 # Server initialized
[37440] 17 Apr 14:21:54.836 * Ready to accept connections [37440] 17 Apr 14:21:54.836 * Ready to accept connections
[7448] 23 Apr 21:40:46.856 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
[7448] 23 Apr 21:40:46.865 # Redis version=5.0.10, bits=64, commit=1c047b68, modified=0, pid=7448, just started
[7448] 23 Apr 21:40:46.865 # Configuration loaded
[7448] 23 Apr 21:40:46.870 * Running mode=standalone, port=6379.
[7448] 23 Apr 21:40:46.870 # Server initialized
[7448] 23 Apr 21:40:46.870 * Ready to accept connections
[35352] 23 Apr 21:42:21.915 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
[35352] 23 Apr 21:42:21.916 # Redis version=5.0.10, bits=64, commit=1c047b68, modified=0, pid=35352, just started
[35352] 23 Apr 21:42:21.916 # Configuration loaded
[35352] 23 Apr 21:42:21.919 * Running mode=standalone, port=6379.
[35352] 23 Apr 21:42:21.919 # Server initialized
[35352] 23 Apr 21:42:21.919 * Ready to accept connections
[30100] 23 Apr 21:42:47.458 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
[30100] 23 Apr 21:42:47.459 # Redis version=5.0.10, bits=64, commit=1c047b68, modified=0, pid=30100, just started
[30100] 23 Apr 21:42:47.460 # Configuration loaded
[30100] 23 Apr 21:42:47.462 * Running mode=standalone, port=6379.
[30100] 23 Apr 21:42:47.462 # Server initialized
[30100] 23 Apr 21:42:47.463 * Ready to accept connections
[29296] 23 Apr 21:43:12.174 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
[29296] 23 Apr 21:43:12.175 # Redis version=5.0.10, bits=64, commit=1c047b68, modified=0, pid=29296, just started
[29296] 23 Apr 21:43:12.175 # Configuration loaded
[29296] 23 Apr 21:43:12.177 * Running mode=standalone, port=6379.
[29296] 23 Apr 21:43:12.177 # Server initialized
[29296] 23 Apr 21:43:12.178 * Ready to accept connections
[29296] 23 Apr 21:43:54.627 # User requested shutdown...
[29296] 23 Apr 21:43:54.629 # Redis is now ready to exit, bye bye...
[14828] 23 Apr 21:45:11.834 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
[14828] 23 Apr 21:45:11.834 # Redis version=5.0.10, bits=64, commit=1c047b68, modified=0, pid=14828, just started
[14828] 23 Apr 21:45:11.835 # Configuration loaded
[14828] 23 Apr 21:45:11.837 * Running mode=standalone, port=6379.
[14828] 23 Apr 21:45:11.837 # Server initialized
[14828] 23 Apr 21:45:11.837 * Ready to accept connections

Loading…
Cancel
Save