首页 > 编程语言 >java项目中使用oshi搭建监控系统

java项目中使用oshi搭建监控系统

时间:2022-11-30 15:39:47浏览次数:55  
标签:return BigDecimal ip static put java byte oshi 搭建


官网地址:​​https://github.com/oshi/oshi​

首先引入jar包

<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>5.2.0</version>
</dependency>

<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.5.0</version>
</dependency>

贴上案例代码:

package com.hw.hwtest;

import com.hw.util.Arith;
import com.hw.util.IpUtils;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.hardware.CentralProcessor.TickType;
import oshi.util.Util;

import java.net.UnknownHostException;
import java.util.*;


public class HwTestApplicationTests {

private static Map<String, Object> cpuMap = new HashMap<>();
private static Map<String, Object> memMap = new HashMap<>();
private static Map<String, Object> sysMap = new HashMap<>();
private static Map<String, Object> jvmMap = new HashMap<>();
private static List<Map<String, Object>> sysFilesMap = new ArrayList<>();





public static void main(String[] args) throws UnknownHostException {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();
setCpuInfo(hal.getProcessor());
setMemInfo(hal.getMemory());
setSysInfo();
setJvmInfo();
setSysFiles(si.getOperatingSystem());
System.out.println("CPU:"+cpuMap.toString());
System.out.println("内存:"+memMap.toString());
System.out.println("系统:"+sysMap.toString());
System.out.println("jvm:"+jvmMap.toString());
System.out.println("磁盘:"+sysFilesMap.toString());

}

/**
* 设置CPU信息
*/
private static void setCpuInfo(CentralProcessor processor) {
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
//这里不休眠的话获取不到cpu信息
Util.sleep(1000);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
cpuMap.put("CpuNum", processor.getLogicalProcessorCount());
cpuMap.put("Total", totalCpu);
cpuMap.put("Sys", cSys);
cpuMap.put("Used", user);
cpuMap.put("Wait", iowait);
cpuMap.put("Free", idle);
}

/**
* 设置内存信息
*/
private static void setMemInfo(GlobalMemory memory) {
memMap.put("Total", memory.getTotal());
memMap.put("Used", memory.getTotal() - memory.getAvailable());
memMap.put("Free", memory.getAvailable());
}

/**
* 设置服务器信息
*/
private static void setSysInfo() {
Properties props = System.getProperties();
sysMap.put("ComputerName", IpUtils.getHostName());
sysMap.put("ComputerIp", IpUtils.getHostIp());
sysMap.put("OsName", props.getProperty("os.name"));
sysMap.put("OsArch", props.getProperty("os.arch"));
sysMap.put("UserDir", props.getProperty("user.dir"));

}

/**
* 设置Java虚拟机
*/
private static void setJvmInfo() throws UnknownHostException {
Properties props = System.getProperties();
jvmMap.put("Total", Runtime.getRuntime().totalMemory());
jvmMap.put("Max", Runtime.getRuntime().maxMemory());
jvmMap.put("Free", Runtime.getRuntime().freeMemory());
jvmMap.put("Version", props.getProperty("java.version"));
jvmMap.put("Home", props.getProperty("java.home"));

}

/**
* 设置磁盘信息
*/
private static void setSysFiles(OperatingSystem os) {
FileSystem fileSystem = os.getFileSystem();
List<OSFileStore> fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
Map<String, Object> sysFile = new HashMap();
sysFile.put("DirName", fs.getMount());
sysFile.put("SysTypeName", fs.getType());
sysFile.put("TypeName", fs.getName());
sysFile.put("Total",convertFileSize(total));
sysFile.put("Free", convertFileSize(free));
sysFile.put("Used",convertFileSize(used));
sysFile.put("Usage", Arith.mul(Arith.div(used, total, 4), 100));

sysFilesMap.add( sysFile);
}
}

/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public static String convertFileSize(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else {
return String.format("%d B", size);
}
}
}

贴上案例结果:

置于前端怎么展示  各位可以自行决定,贴上帮助类代码

 有帮助的话可以点个赞  加一下关注

package com.hw.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
* 精确的浮点数运算
*
* @author ruoyi
*/
public class Arith
{

/** 默认除法运算精度 */
private static final int DEF_DIV_SCALE = 10;

/** 这个类不能实例化 */
private Arith()
{
}

/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}

/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}

/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2)
{
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}

/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2)
{
return div(v1, v2, DEF_DIV_SCALE);
}

/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
if (b1.compareTo(BigDecimal.ZERO) == 0)
{
return BigDecimal.ZERO.doubleValue();
}
return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
}

/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale)
{
if (scale < 0)
{
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
}
}
package com.hw.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* 获取IP方法
*
* @author ruoyi
*/
public class IpUtils {
public static String getIpAddr(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}

if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}

return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}

public static boolean internalIp(String ip) {
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}

private static boolean internalIp(byte[] addr) {
if (addr == null || new String(addr).equals("") || addr.length < 2) {
return true;
}
final byte b0 = addr[0];
final byte b1 = addr[1];
// 10.x.x.x/8
final byte SECTION_1 = 0x0A;
// 172.16.x.x/12
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0) {
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4) {
return true;
}
case SECTION_5:
switch (b1) {
case SECTION_6:
return true;
}
default:
return false;
}
}

/**
* 将IPv4地址转换成字节
*
* @param text IPv4地址
* @return byte 字节
*/
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
}

byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try {
long l;
int i;
switch (elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L)) {
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L)) {
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L)) {
return null;
}
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
} catch (NumberFormatException e) {
return null;
}
return bytes;
}

public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
}
return "127.0.0.1";
}

public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
}
return "未知";
}
}

 

标签:return,BigDecimal,ip,static,put,java,byte,oshi,搭建
From: https://blog.51cto.com/u_15897407/5899806

相关文章

  • JAVA规定时间循环定时执行某个任务
    在我们做web项目的时候有些需求需要我们定时每周每天执行什么任务,这里给大家介绍一种方式,我就直接贴代码web.xml<listener><listener-class>com.hw.util.BeginRun......
  • 使用Prometheus+Grafana搭建服务器监控系统
    安装$wgethttps://github.com/prometheus/prometheus/releases/download/v2.7.2/prometheus-2.7.2.linux-amd64.tar.gz$tarxvfzprometheus-2.7.2.linux-amd64.tar.gz$......
  • [JavaScript] 自顶向下学习如何手写promise
    引子去年写了一篇有关promise的手写文章,写到一半发现自己的理解还不是很透彻,写的很烂,今年卷土重来,实现部分采用功能分解,目录跳转的形式呈现,力求最通俗易懂得剖析promise,我......
  • Java生成帮助文档
    在要生成帮助文档的目录下打开cmd   输入javadoc-encodingUTF-8-charrsetUTF-8要生成的Java文件  在生成的文件中打开index.html......
  • Java基础
    注释平时我们编写代码,在代码量很少时,我们还可以看懂自己写的,但当项目结构一旦复杂起来,我们就需要用到注释了注释并不会被执行,是给我们写代码的人看的书写注释是......
  • Java基础----内部类
    内部类分为1.成员内部类2.静态内部类3.局部内部类4.匿名内部类内部类概念:在一个类的内部再定义一个类特点:编译之后可以独立生成独立的字节码文件内部类可以......
  • java并发编程(二十二)-并发安全的基本概念
    类的线程安全定义  如果多线程下使用这个类,不过多线程如何使用和调度这个类,这个类总是表示出正确的行为,这个类就是线程安全的。类的线程安全表现为:操作的原子性内存的可见......
  • java并发编程(二十三)-并发安全之死锁
    死锁资源一定是多于1个,同时小于等于竞争的线程数,资源只有一个,只会产生激烈的竞争。死锁的根本成因:获取锁的顺序不一致导致。 死锁的一般情况:packagecom.caojiulu;importc......
  • java并发编程(一)-线程相关的基本概念
    CPU核心数和线程数的关系核心数:线程数=1:1intel引入超线程技术之后--》核心数:线程数=1:2CPU时间片轮转机制-又称RR调度 时间片轮转法(Round-Robin,RR)主要用于分时系统......
  • java并发编程(三)-线程的协作式
    怎么样才能让Java里的线程安全停止工作呢?一般来说:程序执行完或者抛出异常。怎么用代码的方式将线程停止呢?可以看到stop(),resume(),suspend()已不建议使用,stop()会导致线程......