之前有一篇博客介绍如何获取Linux服务器上的资源使用情况《Java 获取服务器资源(内存、负载、磁盘容量)》,这里介绍如何通过C#获取Window系统的资源使用。
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);
//定义内存的信息结构
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_INFO {
public uint DWLength;//当前结构体大小
public uint DWMemoryLoad;//当前内存使用率
public ulong ullTotalPhys;//总计物理内存大小
public ulong ullAvailPhys;//可用物理内存代销
public ulong ullTotalPagefiles;//总计交换文件大小
public ulong ullAvailPagefiles;//可用交换文件大小
public ulong ullTotalVirtual;//总计虚拟内存大小
public ulong ullAvailVirtual;//可用虚拟内存大小
}
private static MEMORY_INFO GetMemoryInfo() {
MEMORY_INFO memoryInfo = new MEMORY_INFO();
memoryInfo.DWLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(memoryInfo);
GlobalMemoryStatusEx(ref memoryInfo);
return memoryInfo;
}
///
/// 获取内存信息
///
///
public static ServerMemory GetSysMemoryInfo()
{
try
{
MEMORY_INFO memoryInfo = GetMemoryInfo();
ServerMemory serverMemory = new ServerMemory();
serverMemory.serverId = serverId;
serverMemory.serverName = serverName;
serverMemory.memTotal = (uint)(memoryInfo.ullTotalPhys / 1024);
serverMemory.memFree = (uint)(memoryInfo.ullTotalPagefiles / 1024);
serverMemory.memAvailable = (uint)(memoryInfo.ullAvailPhys / 1024);
serverMemory.active = (uint)(memoryInfo.ullAvailPhys/1024);
long timestamp = CommonUtil.getNowDateTimestamp();
serverMemory.dateTimestamp = timestamp;
serverMemory.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverMemory;
}
catch (Exception ex) {
Log.Instance.Error("GetSysMemoryInfo:" + ex.Message);
return null;
}
}
因为获取到的资源是以byte为单位,我这里将其转成了KB,所以除以了1024.
ServerMemory实体类
public class ServerMemory
{
public string serverId { set; get; }
public string serverName { set; get; }
///
/// 内存总量
///
public uint memTotal { set; get; }
///
/// 系统保留量
///
public uint memFree { set; get; }
///
/// 应用程序可用量
///
public uint memAvailable { set; get; }
///
/// 可使用量
///
public uint active { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}
public static ServerDisk GetUsedDisk() {
try
{
List> diskInfoList = new List>();
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = diskClass.GetInstances();
foreach (ManagementObject disk in disks)
{
Dictionary diskInfoDic = new Dictionary();
try
{
// 磁盘名称
diskInfoDic["Name"] = disk["Name"].ToString();
// 磁盘描述
diskInfoDic["Description"] = disk["Description"].ToString();
// 磁盘总容量,可用空间,已用空间
if (System.Convert.ToInt64(disk["Size"]) > 0)
{
long totalSpace = System.Convert.ToInt64(disk["Size"]) / 1024;
long freeSpace = System.Convert.ToInt64(disk["FreeSpace"]) / 1024;
long usedSpace = totalSpace - freeSpace;
diskInfoDic["totalSpace"] = totalSpace.ToString();
diskInfoDic["usedSpace"] = usedSpace.ToString();
diskInfoDic["freeSpace"] = freeSpace.ToString();
}
diskInfoList.Add(diskInfoDic);
}
catch (Exception ex)
{
Log.Instance.Error("ManagementObject->disk:" + ex.Message);
}
}
if (diskInfoList.Count > 0)
{
ServerDisk serverDisk = new ServerDisk();
serverDisk.serverId = serverId;
serverDisk.serverName = serverName;
Dictionary diskMap = new Dictionary();
foreach (Dictionary dic in diskInfoList)
{
if (dic.ContainsKey("totalSpace") && dic.ContainsKey("usedSpace") && dic.ContainsKey("freeSpace"))
{
DiskInfo diskInfo = new DiskInfo();
diskInfo.diskName = dic["Name"];
diskInfo.diskSize = double.Parse(dic["totalSpace"]);
diskInfo.used = double.Parse(dic["usedSpace"]);
diskInfo.avail = double.Parse(dic["freeSpace"]);
diskInfo.usageRate = (int)((diskInfo.used / diskInfo.diskSize) * 100);
diskMap.Add(diskInfo.diskName, diskInfo);
}
}
serverDisk.diskInfoMap = diskMap;
long timestamp = CommonUtil.getNowDateTimestamp();
serverDisk.dateTimestamp = timestamp;
serverDisk.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverDisk;
}
else
{
return null;
}
}
catch (Exception ex) {
Log.Instance.Error("GetUsedDisk:"+ex.Message);
return null;
}
}
ServerDisk实体类
public class ServerDisk
{
public string serverId { set; get; }
public string serverName { set; get; }
public Dictionary diskInfoMap { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}
DiskInfo实体类
public class DiskInfo
{
public string diskName { set; get; }
public double diskSize { set; get; }
public double used { set; get; }
public double avail { set; get; }
public int usageRate { set; get; }
}
public static ServerCpu GetUsedCPU() {
ManagementClass mc = new ManagementClass("Win32_PerfFormattedData_PerfOs_Processor");
ManagementObjectCollection moc = mc.GetInstances();
List list = new List ();
foreach (ManagementObject mo in moc) {
if (mo["Name"].ToString() == "_Total") {
list.Add(mo["percentprocessorTime"].ToString());
}
}
int percentage = list.Sum(s => int.Parse(s));
ServerCpu serverCpu = new ServerCpu();
serverCpu.serverId = serverId;
serverCpu.serverName = serverName;
serverCpu.percentage = percentage;
long timestamp = CommonUtil.getNowDateTimestamp();
serverCpu.dateTimestamp = timestamp;
serverCpu.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverCpu;
}
ServerCpu实体类
public class ServerCpu
{
public string serverId { set; get; }
public string serverName { set; get; }
public int percentage { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}
最终我想实现对Linux和Windows服务器的监控,类似效果如下: