修改项目结构
This commit is contained in:
150
Infrastructure/Helper/ComputerHelper.cs
Normal file
150
Infrastructure/Helper/ComputerHelper.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
using Infrastructure.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class ComputerHelper
|
||||
{
|
||||
public static ComputerInfo GetComputerInfo()
|
||||
{
|
||||
ComputerInfo computerInfo = new ComputerInfo();
|
||||
try
|
||||
{
|
||||
MemoryMetricsClient client = new MemoryMetricsClient();
|
||||
MemoryMetrics memoryMetrics = client.GetMetrics();
|
||||
computerInfo.TotalRAM = Math.Ceiling(memoryMetrics.Total / 1024).ToString() + " GB";
|
||||
computerInfo.RAMRate = Math.Ceiling(100 * memoryMetrics.Used / memoryMetrics.Total).ToString() + " %";
|
||||
computerInfo.CPURate = Math.Ceiling(GetCPURate().ParseToDouble()) + " %";
|
||||
computerInfo.RunTime = GetRunTime();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//LogHelper.Error(ex);
|
||||
}
|
||||
return computerInfo;
|
||||
}
|
||||
|
||||
public static bool IsUnix()
|
||||
{
|
||||
var isUnix = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
|
||||
return isUnix;
|
||||
}
|
||||
|
||||
public static string GetCPURate()
|
||||
{
|
||||
string cpuRate = string.Empty;
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("top -b -n1 | grep \"Cpu(s)\" | awk '{print $2 + $4}'");
|
||||
cpuRate = output.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "cpu get LoadPercentage");
|
||||
cpuRate = output.Replace("LoadPercentage", string.Empty).Trim();
|
||||
}
|
||||
return cpuRate;
|
||||
}
|
||||
|
||||
public static string GetRunTime()
|
||||
{
|
||||
string runTime = string.Empty;
|
||||
try
|
||||
{
|
||||
if (IsUnix())
|
||||
{
|
||||
string output = ShellHelper.Bash("uptime -s");
|
||||
output = output.Trim();
|
||||
runTime = DateTimeHelper.FormatTime((DateTime.Now - output.ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
|
||||
}
|
||||
else
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get LastBootUpTime/Value");
|
||||
string[] outputArr = output.Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
|
||||
if (outputArr.Length == 2)
|
||||
{
|
||||
runTime = DateTimeHelper.FormatTime((DateTime.Now - outputArr[1].Split('.')[0].ParseToDateTime()).TotalMilliseconds.ToString().Split('.')[0].ParseToLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//LogHelper.Error(ex);
|
||||
}
|
||||
return runTime;
|
||||
}
|
||||
}
|
||||
|
||||
public class MemoryMetrics
|
||||
{
|
||||
public double Total { get; set; }
|
||||
public double Used { get; set; }
|
||||
public double Free { get; set; }
|
||||
}
|
||||
|
||||
public class MemoryMetricsClient
|
||||
{
|
||||
public MemoryMetrics GetMetrics()
|
||||
{
|
||||
if (ComputerHelper.IsUnix())
|
||||
{
|
||||
return GetUnixMetrics();
|
||||
}
|
||||
return GetWindowsMetrics();
|
||||
}
|
||||
|
||||
private MemoryMetrics GetWindowsMetrics()
|
||||
{
|
||||
string output = ShellHelper.Cmd("wmic", "OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
|
||||
|
||||
var lines = output.Trim().Split('\n');
|
||||
var freeMemoryParts = lines[0].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
|
||||
var totalMemoryParts = lines[1].Split('=', (char)StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = Math.Round(double.Parse(totalMemoryParts[1]) / 1024, 0);
|
||||
metrics.Free = Math.Round(double.Parse(freeMemoryParts[1]) / 1024, 0);
|
||||
metrics.Used = metrics.Total - metrics.Free;
|
||||
|
||||
return metrics;
|
||||
}
|
||||
|
||||
private MemoryMetrics GetUnixMetrics()
|
||||
{
|
||||
string output = ShellHelper.Bash("free -m");
|
||||
|
||||
var lines = output.Split('\n');
|
||||
var memory = lines[1].Split(' ', (char)StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var metrics = new MemoryMetrics();
|
||||
metrics.Total = double.Parse(memory[1]);
|
||||
metrics.Used = double.Parse(memory[2]);
|
||||
metrics.Free = double.Parse(memory[3]);
|
||||
|
||||
return metrics;
|
||||
}
|
||||
}
|
||||
|
||||
public class ComputerInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// CPU使用率
|
||||
/// </summary>
|
||||
public string CPURate { get; set; }
|
||||
/// <summary>
|
||||
/// 总内存
|
||||
/// </summary>
|
||||
public string TotalRAM { get; set; }
|
||||
/// <summary>
|
||||
/// 内存使用率
|
||||
/// </summary>
|
||||
public string RAMRate { get; set; }
|
||||
/// <summary>
|
||||
/// 系统运行时间
|
||||
/// </summary>
|
||||
public string RunTime { get; set; }
|
||||
}
|
||||
}
|
||||
100
Infrastructure/Helper/DateTimeHelper.cs
Normal file
100
Infrastructure/Helper/DateTimeHelper.cs
Normal file
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class DateTimeHelper
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="dateTime"></param>
|
||||
/// <returns></returns>
|
||||
public static DateTime GetBeginTime(DateTime? dateTime, int days = 0)
|
||||
{
|
||||
if (dateTime == DateTime.MinValue || dateTime == null)
|
||||
{
|
||||
return DateTime.Now.AddDays(days);
|
||||
}
|
||||
return dateTime ?? DateTime.Now;
|
||||
}
|
||||
|
||||
#region 毫秒转天时分秒
|
||||
/// <summary>
|
||||
/// 毫秒转天时分秒
|
||||
/// </summary>
|
||||
/// <param name="ms"></param>
|
||||
/// <returns></returns>
|
||||
public static string FormatTime(long ms)
|
||||
{
|
||||
int ss = 1000;
|
||||
int mi = ss * 60;
|
||||
int hh = mi * 60;
|
||||
int dd = hh * 24;
|
||||
|
||||
long day = ms / dd;
|
||||
long hour = (ms - day * dd) / hh;
|
||||
long minute = (ms - day * dd - hour * hh) / mi;
|
||||
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
|
||||
long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
|
||||
|
||||
string sDay = day < 10 ? "0" + day : "" + day; //天
|
||||
string sHour = hour < 10 ? "0" + hour : "" + hour;//小时
|
||||
string sMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
|
||||
string sSecond = second < 10 ? "0" + second : "" + second;//秒
|
||||
string sMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒
|
||||
sMilliSecond = milliSecond < 100 ? "0" + sMilliSecond : "" + sMilliSecond;
|
||||
|
||||
return string.Format("{0} 天 {1} 小时 {2} 分 {3} 秒", sDay, sHour, sMinute, sSecond);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取unix时间戳
|
||||
/// <summary>
|
||||
/// 获取unix时间戳
|
||||
/// </summary>
|
||||
/// <param name="dt"></param>
|
||||
/// <returns></returns>
|
||||
public static long GetUnixTimeStamp(DateTime dt)
|
||||
{
|
||||
long unixTime = ((DateTimeOffset)dt).ToUnixTimeMilliseconds();
|
||||
return unixTime;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取日期天的最小时间
|
||||
public static DateTime GetDayMinDate(DateTime dt)
|
||||
{
|
||||
DateTime min = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0);
|
||||
return min;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取日期天的最大时间
|
||||
public static DateTime GetDayMaxDate(DateTime dt)
|
||||
{
|
||||
DateTime max = new DateTime(dt.Year, dt.Month, dt.Day, 23, 59, 59);
|
||||
return max;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 获取日期天的最大时间
|
||||
public static string FormatDateTime(DateTime? dt)
|
||||
{
|
||||
if (dt != null)
|
||||
{
|
||||
if (dt.Value.Year == DateTime.Now.Year)
|
||||
{
|
||||
return dt.Value.ToString("MM-dd HH:mm");
|
||||
}
|
||||
else
|
||||
{
|
||||
return dt.Value.ToString("yyyy-MM-dd HH:mm");
|
||||
}
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
48
Infrastructure/Helper/FileUtil.cs
Normal file
48
Infrastructure/Helper/FileUtil.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class FileUtil
|
||||
{
|
||||
/// <summary>
|
||||
/// 按时间来创建文件夹
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <returns>eg: /{yourPath}/2020/11/3</returns>
|
||||
public static string GetdirPath(string path = "")
|
||||
{
|
||||
DateTime date = DateTime.Now;
|
||||
int year = date.Year;
|
||||
int month = date.Month;
|
||||
int day = date.Day;
|
||||
int hour = date.Hour;
|
||||
|
||||
string timeDir = $"{year}/{month}/{day}/{hour}";// date.ToString("yyyyMM/dd/HH/");
|
||||
|
||||
if (!string.IsNullOrEmpty(path))
|
||||
{
|
||||
timeDir = $"{path}/{timeDir}";
|
||||
}
|
||||
return timeDir;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取文件名的MD5值(16位)
|
||||
/// </summary>
|
||||
/// <param name="name">文件名,不包括扩展名</param>
|
||||
/// <returns></returns>
|
||||
public static string HashFileName(string str = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(str))
|
||||
{
|
||||
str = Guid.NewGuid().ToString();
|
||||
}
|
||||
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
|
||||
return BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(str)), 4, 8).Replace("-", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
128
Infrastructure/Helper/HttpHelper.cs
Normal file
128
Infrastructure/Helper/HttpHelper.cs
Normal file
@@ -0,0 +1,128 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class HttpHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 发起POST同步请求
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="postData"></param>
|
||||
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
|
||||
/// <param name="headers">填充消息头</param>
|
||||
/// <returns></returns>
|
||||
public static string HttpPost(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
|
||||
{
|
||||
postData = postData ?? "";
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
if (headers != null)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
|
||||
{
|
||||
if (contentType != null)
|
||||
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
|
||||
|
||||
HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
|
||||
return response.Content.ReadAsStringAsync().Result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 发起POST异步请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="postData"></param>
|
||||
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
|
||||
/// <param name="headers">填充消息头</param>
|
||||
/// <returns></returns>
|
||||
public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
|
||||
{
|
||||
postData = postData ?? "";
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
client.Timeout = new TimeSpan(0, 0, timeOut);
|
||||
if (headers != null)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
|
||||
{
|
||||
if (contentType != null)
|
||||
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
|
||||
|
||||
HttpResponseMessage response = await client.PostAsync(url, httpContent);
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发起GET同步请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <returns></returns>
|
||||
public static string HttpGet(string url, Dictionary<string, string> headers = null)
|
||||
{
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
if (headers != null)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded");
|
||||
client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
|
||||
}
|
||||
try
|
||||
{
|
||||
HttpResponseMessage response = client.GetAsync(url).Result;
|
||||
return response.Content.ReadAsStringAsync().Result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//TODO 打印日志
|
||||
Console.WriteLine($"[Http请求出错]{url}|{ex.Message}");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发起GET异步请求
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="headers"></param>
|
||||
/// <param name="contentType"></param>
|
||||
/// <returns></returns>
|
||||
public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
|
||||
{
|
||||
using (HttpClient client = new HttpClient())
|
||||
{
|
||||
if (headers != null)
|
||||
{
|
||||
foreach (var header in headers)
|
||||
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
||||
}
|
||||
HttpResponseMessage response = await client.GetAsync(url);
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
47
Infrastructure/Helper/ShellHelper.cs
Normal file
47
Infrastructure/Helper/ShellHelper.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace Infrastructure
|
||||
{
|
||||
public class ShellHelper
|
||||
{
|
||||
public static string Bash(string command)
|
||||
{
|
||||
var escapedArgs = command.Replace("\"", "\\\"");
|
||||
var process = new Process()
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = "/bin/bash",
|
||||
Arguments = $"-c \"{escapedArgs}\"",
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
}
|
||||
};
|
||||
process.Start();
|
||||
string result = process.StandardOutput.ReadToEnd();
|
||||
process.WaitForExit();
|
||||
process.Dispose();
|
||||
return result;
|
||||
}
|
||||
|
||||
public static string Cmd(string fileName, string args)
|
||||
{
|
||||
string output = string.Empty;
|
||||
|
||||
var info = new ProcessStartInfo();
|
||||
info.FileName = fileName;
|
||||
info.Arguments = args;
|
||||
info.RedirectStandardOutput = true;
|
||||
|
||||
using (var process = Process.Start(info))
|
||||
{
|
||||
output = process.StandardOutput.ReadToEnd();
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user