• 获取Linux系统信息工具类


    导包

    
            <dependency>
                <groupId>com.github.oshigroupId>
                <artifactId>oshi-coreartifactId>
                <version>6.4.0version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    全局格式化时间

      jackson:
        # 格式化全局时间字段 年-月-天 时:分:秒
        date-format: yyyy-MM-dd HH:mm:ss
        # 指定时间区域类型 东8区时区 既北京时间
        time-zone: GMT+8
    
    • 1
    • 2
    • 3
    • 4
    • 5

    DiskInfo实体类

    
    import lombok.Data;
    
    /**
     * 磁盘信息封装类
     *
     */
    @Data
    public class DisksInfo {
    
        /**
         * 文件系统的挂载点
         */
        private String dirName;
    
        /**
         * 文件系统名称
         */
        private String sysTypeName;
    
        /**
         * 文件系统的类型(FAT,NTFS,etx2,ext4等)
         */
        private String typeName;
    
        /**
         * 总大小
         */
        private long total;
    
        /**
         * 剩余大小
         */
        private long free;
    
        /**
         * 已经使用量
         */
        private long used;
    
        /**
         * 资源的使用率
         */
        private String usage;
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    NetworkInfo实体类

    
    import lombok.Data;
    
    import java.util.List;
    
    /**
     * 网卡信息包装类
     *
     */
    @Data
    public class NetworkInfo {
    
        /**
         * ipv4地址
         */
        private String ipv4Address;
    
        /**
         * ipv6地址
         */
        private String ipv6Address;
    
        /**
         * mac地址
         */
        private String macAddress;
    
        /**
         * 网卡名称
         */
        private String networkName;
    
        /**
         * 发送数据量
         */
        private long send;
    
        /**
         * 接受数据量
         */
        private long accept;
    
        /**
         * 网卡时间戳
         */
        private long timeStamp;
    
        /**
         * 子网掩码
         */
        private String subnetMask;
    
        /**
         * 前缀长度
         */
        private String prefixLength;
    
        /**
         * 首选dns服务器地址
         */
        private String preferredDnsServer;
    
        /**
         * 备选dns服务器地址
         */
        private String alternateDnsServer;
    
        /**
         * IPV4网关地址
         */
        private String ipv4Gateway;
    
        /**
         * IPV6网关地址
         */
        private String ipv6Gateway;
    
    
    
    
    }
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85

    OSInfo实体类

    
    import lombok.Data;
    
    import java.util.Date;
    import java.util.List;
    
    /**
     * 系统信息
     *
     */
    @Data
    public class OSInfo {
    
        /**
         * 系统
         */
        private String os;
    
        /**
         * 系统架构
         */
        private String osArch;
    
        /**
         * java版本
         */
        private String javaVersion;
    
        /**
         * 工作目录
         */
        private String userDir;
    
        /**
         * cpu核心数
         */
        private int cpuCount;
    
        /**
         * 主机host
         */
        private String host;
    
        /**
         * 主机名称
         */
        private String hostName;
    
        /**
         * 系统时间
         */
        private Date sysTime;
    
        /**
         * 产品
         */
        private String model;
    
        /**
         * 序列号
         */
        private String serialNumber;
    
        /**
         * 系统已启动时间
         */
        private String bootTime;
    
        /**
         * 系统内存使用率
         */
        private String usage;
    
        /**
         * 磁盘信息
         */
        private List<DisksInfo> disksList;
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    OSRuntimeInfo

    
    import com.yuyin.ippbx.vo.systeminfo.DisksInfo;
    import com.yuyin.ippbx.vo.systeminfo.NetworkInfo;
    import lombok.Data;
    
    import java.util.List;
    
    /**
     * 系统运行时信息
     *
     */
    @Data
    public class OSRuntimeInfo {
    
        /**
         * 时刻
         */
        private String timestamp;
    
        /**
         * cpu使用率
         */
        private double cpuUsage;
    
        /**
         * cpu基准速度(GHz)
         */
        private String cpuMaxFreq;
    
        /**
         * cpu当前速度(GHz)
         */
        private String cpuCurrentFreq;
    
        /**
         * 总内存
         */
        private long totalMemory;
    
        /**
         * 使用内存
         */
        private long usedMemory;
    
        /**
         * 可用虚拟总内存
         */
        private long swapTotalMemory;
    
        /**
         * 已用虚拟内存
         */
        private long swapUsedMemory;
    
        /**
         * 磁盘信息
         */
        private List<DisksInfo> disksList;
    
        /**
         * 磁盘读取速率(Kb/s)
         */
        private Double diskReadRate;
    
        /**
         * 磁盘写入速率(Kb/s)
         */
        private Double diskWriteRate;
    
        /**
         * 网卡信息
         */
        private List<NetworkInfo> networkList;
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    获取信息工具类

    
    
    import cn.hutool.core.collection.ListUtil;
    import cn.hutool.core.date.DatePattern;
    import cn.hutool.core.date.DateTime;
    import cn.hutool.core.date.DateUtil;
    import cn.hutool.core.io.unit.DataUnit;
    import cn.hutool.core.util.StrUtil;
    import cn.hutool.system.oshi.OshiUtil;
    import com.yuyin.ippbx.vo.systeminfo.DisksInfo;
    import com.yuyin.ippbx.vo.systeminfo.NetworkInfo;
    import com.yuyin.ippbx.vo.systeminfo.OSInfo;
    import com.yuyin.ippbx.vo.systeminfo.OSRuntimeInfo;
    import lombok.extern.slf4j.Slf4j;
    import org.junit.jupiter.api.Test;
    import oshi.PlatformEnum;
    import oshi.SystemInfo;
    import oshi.hardware.CentralProcessor;
    import oshi.hardware.GlobalMemory;
    import oshi.hardware.HardwareAbstractionLayer;
    import oshi.hardware.NetworkIF;
    import oshi.software.os.FileSystem;
    import oshi.software.os.NetworkParams;
    import oshi.software.os.OSFileStore;
    import oshi.software.os.OperatingSystem;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.nio.charset.Charset;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.TimeUnit;
    
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.*;
    
    /**
     * 系统信息获取工具类
     * 1.操作系统信息
     * 2.系统cpu使用信息
     * 3.系统内存信息
     * 4.系统卡流量信息
     * 5.磁盘使用量信息
     */
    @Slf4j
    public class SystemInfoUtil {
    
        private static SystemInfo systemInfo;
    
        private static HardwareAbstractionLayer abstractionLayer;
    
        private static OperatingSystem operatingSystem;
    
        private static CentralProcessor centralProcessor;
    
        private static GlobalMemory globalMemory;
    
        private static long[] oldTicks;
    
        private static Map<String, Long[]> networkInfoMap;
    
        private static List<NetworkIF> networkIFList;
    
        private static DecimalFormat df = new DecimalFormat("0.00");
    
        private SystemInfoUtil() {
        }
    
    
        static {
            try {
                systemInfo = new SystemInfo();
                abstractionLayer = systemInfo.getHardware();
                operatingSystem = systemInfo.getOperatingSystem();
                centralProcessor = abstractionLayer.getProcessor();
                globalMemory = abstractionLayer.getMemory();
                oldTicks = new long[CentralProcessor.TickType.values().length];
                networkInfoMap = new ConcurrentHashMap<>();
                networkIFList = getNetwork();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        enum NetworkType {
            /**
             * 当前网卡时间戳
             */
            TIME_STAMP(0),
            /**
             * 网卡总发送量
             */
            SEND(1),
            /**
             * 网卡总接收量
             */
            ACCEPT(2);
            private int index;
    
            NetworkType(int value) {
                this.index = value;
            }
    
            public int getIndex() {
                return index;
            }
        }
    
        /**
         * 获取磁盘列表信息
         *
         * @return
         */
        public static List<DisksInfo> getDisksList() {
            FileSystem fileSystem = operatingSystem.getFileSystem();
            List<OSFileStore> fileStores = fileSystem.getFileStores();
            List<DisksInfo> list = new ArrayList<>();
            for (int i = 0; i < fileStores.size(); i++) {
                OSFileStore osFileStore = fileStores.get(i);
                DisksInfo disksInfo = new DisksInfo();
                disksInfo.setDirName(osFileStore.getMount());
                String name = osFileStore.getName();
                disksInfo.setSysTypeName(name);
                disksInfo.setTypeName(osFileStore.getType());
                long total = osFileStore.getTotalSpace();
                long free = osFileStore.getUsableSpace();
                long used = total - free;
                if (used < 0) {
                    // 有的挂载盘获取到的 free比total还大 不知是否是方法问题
                    continue;
                }
                disksInfo.setTotal(total);
                disksInfo.setFree(free);
                disksInfo.setUsed(used);
                if (total != 0) {
                    disksInfo.setUsage(formatRate(Double.parseDouble(df.format((double) used / total))));
                }
                list.add(disksInfo);
            }
            return list;
        }
    
        /**
         * 获取网络接口NetworkIF对象列表
         *
         * @return
         */
        private static List<NetworkIF> getNetwork() {
            List<NetworkIF> list = new ArrayList<>();
            List<NetworkIF> networkIFs = abstractionLayer.getNetworkIFs();
            for (int i = 0; i < networkIFs.size(); i++) {
                NetworkIF networkIF = networkIFs.get(i);
                if (!networkIF.isKnownVmMacAddr()) {
                    if (networkIF.getMacaddr() != null && networkIF.getIPv4addr().length > 0
                            && networkIF.getIPv6addr().length > 0) {
                        if (!networkInfoMap.containsKey(networkIF.getMacaddr())) {
                            networkIF.updateAttributes();
                            Long[] data = new Long[]{networkIF.getTimeStamp(), networkIF.getBytesSent(), networkIF.getBytesRecv()};
                            networkInfoMap.put(networkIF.getMacaddr(), data);
                        }
                        list.add(networkIF);
                    }
                }
            }
            return list;
        }
    
        /**
         * 网卡实际的传输速率受多方面影响,具体如下:
         * 1、硬盘的读写(I/O)速度达不到。
         * 2、网卡本身性能差。
         * 3、交换机/(HUB)性能差。
         * 4、通讯线路条件质量差。
         * 5、网络性能差。
         * 

    * 一般情况下: * 网络条件比较好的网络利用率100Mbits的一般为:1/8(此方法默认) * 网络及各方面条件差的利用率一般为:1/12 */ public static List<NetworkInfo> getNetworkInfo() throws UnknownHostException { networkIFList = getNetwork(); List<NetworkInfo> list = new ArrayList<>(); for (int i = 0; i < networkIFList.size(); i++) { NetworkIF networkIF = networkIFList.get(i); if (networkIF.updateAttributes()) { if (networkIF.getIPv4addr().length > 0 && networkIF.getIPv6addr().length > 0) { NetworkInfo networkInfo = new NetworkInfo(); networkInfo.setIpv4Address(networkIF.getIPv4addr()[0]); networkInfo.setIpv6Address(networkIF.getIPv6addr()[0]); Short prefixLength = networkIF.getSubnetMasks()[0]; // 转换格式 String submask = convertSubMask(prefixLength); networkInfo.setSubnetMask(submask); // 获取mac地址 networkInfo.setMacAddress(networkIF.getMacaddr()); // 获取网络名称 networkInfo.setNetworkName(networkIF.getName()); // 获取网络配置参数:dns || 默认网关 NetworkParams networkParams = operatingSystem.getNetworkParams(); // dns String[] dnsServers = networkParams.getDnsServers(); List<String> strings = Arrays.asList(dnsServers); if (!strings.isEmpty()){ if (strings.get(0) != null){ // 首选dns服务器 networkInfo.setPreferredDnsServer(strings.get(0)); } if (strings.get(1) != null){ // 备选dns服务器 networkInfo.setAlternateDnsServer(strings.get(1)); } } // 网关地址 networkInfo.setIpv4Gateway(networkParams.getIpv4DefaultGateway()); networkInfo.setIpv6Gateway(networkParams.getIpv6DefaultGateway()); networkInfo.setPrefixLength(String.valueOf(networkIF.getPrefixLengths()[0])); // System.out.println("display"+networkIF.getDisplayName()); //计算 Long[] oldData = networkInfoMap.get(networkIF.getMacaddr()); long time = oldData[NetworkType.TIME_STAMP.getIndex()] - networkIF.getTimeStamp(); if (time == 0) { continue; } long send = (oldData[NetworkType.SEND.getIndex()] - networkIF.getBytesSent()) * 8 / time * 1000; long accept = (oldData[NetworkType.ACCEPT.getIndex()] - networkIF.getBytesRecv()) * 8 / time * 1000; Long[] newData = new Long[]{networkIF.getTimeStamp(), networkIF.getBytesSent(), networkIF.getBytesRecv()}; networkInfoMap.put(networkInfo.getMacAddress(), newData); //对象赋值 networkInfo.setTimeStamp(networkIF.getTimeStamp()); networkInfo.setSend(send); networkInfo.setAccept(accept); list.add(networkInfo); } } } return list; } /** * 子网掩码转换格式 */ public static String convertSubMask(short prflen){ int shft = 0xffffffff<<(32-prflen); int oct1 = ((byte) ((shft&0xff000000)>>24)) & 0xff; int oct2 = ((byte) ((shft&0x00ff0000)>>16)) & 0xff; int oct3 = ((byte) ((shft&0x0000ff00)>>8)) & 0xff; int oct4 = ((byte) (shft&0x000000ff)) & 0xff; String submask = oct1+"."+oct2+"."+oct3+"."+oct4; return submask; } /** * 获取系统运行信息 * * @return * @throws InterruptedException */ public static OSRuntimeInfo getOSRuntimeInfo() throws InterruptedException, UnknownHostException { OSRuntimeInfo osRuntimeInfo = new OSRuntimeInfo(); osRuntimeInfo.setTimestamp(DateUtil.now()); //cpu使用率 osRuntimeInfo.setCpuUsage(getCpuRate()); //cpu基准速度(GHz) osRuntimeInfo.setCpuMaxFreq(df.format(centralProcessor.getMaxFreq() / 1000000000.0) + " GHz"); //cpu当前速度(GHz) long[] currentFreq = centralProcessor.getCurrentFreq(); long avg = Arrays.stream(currentFreq).sum() / currentFreq.length; osRuntimeInfo.setCpuCurrentFreq(df.format(avg / 1000000000.0) + " GHz"); //系统内存总量 osRuntimeInfo.setTotalMemory(globalMemory.getTotal()); //系统使用量 osRuntimeInfo.setUsedMemory(globalMemory.getTotal() - globalMemory.getAvailable()); //可用虚拟总内存 osRuntimeInfo.setSwapTotalMemory(globalMemory.getVirtualMemory().getSwapTotal()); //已用虚拟内存 osRuntimeInfo.setSwapUsedMemory(globalMemory.getVirtualMemory().getSwapUsed()); //磁盘信息 osRuntimeInfo.setDisksList(getDisksList()); //磁盘读取速率 Map<String, Double> diskIo = getDiskIo(); double diskReadRate = diskIo.get("diskReadRate"); osRuntimeInfo.setDiskReadRate(diskReadRate); //磁盘写入速率 double diskWriteRate = diskIo.get("diskWriteRate"); osRuntimeInfo.setDiskWriteRate(diskWriteRate); //网卡信息 osRuntimeInfo.setNetworkList(getNetworkInfo()); return osRuntimeInfo; } public static OSInfo getSystemInfo() throws UnknownHostException, InterruptedException { Properties props = System.getProperties(); String model = OshiUtil.getHardware().getComputerSystem().getModel(); String serialNumber = OshiUtil.getHardware().getComputerSystem().getSerialNumber(); OSInfo osInfo = new OSInfo(); //操作系统 osInfo.setOs(props.getProperty("os.name")); //系统架构 osInfo.setOsArch(props.getProperty("os.arch")); //java版本 osInfo.setJavaVersion(props.getProperty("java.version")); //工作目录 osInfo.setUserDir(props.getProperty("user.dir")); //CPU核数 osInfo.setCpuCount(centralProcessor.getLogicalProcessorCount()); // 系统时间 osInfo.setSysTime(DateUtil.date()); // 产品 osInfo.setModel(model); // 版本号 osInfo.setSerialNumber(serialNumber); //主机信息 try { InetAddress address = InetAddress.getLocalHost(); osInfo.setHost(address.getHostAddress()); osInfo.setHostName(address.getHostName()); } catch (UnknownHostException e) { log.error("主机信息获取失败"); } //系统已启动时间 String runTime = ""; if (StrUtil.isNotEmpty(getBootTime())) { DateTime start = DateUtil.parse(getBootTime(), DatePattern.NORM_DATETIME_PATTERN); runTime = DateUtil.formatBetween(start, DateUtil.date()); } osInfo.setBootTime(runTime); long total = globalMemory.getTotal(); long used = globalMemory.getTotal() - globalMemory.getAvailable(); double usage = used * 1.0 / total; // 系统内存使用率 osInfo.setUsage(formatRate(usage)); // log.info("usage: " + String.valueOf(usage)); // log.info("format usage: " + String.valueOf(formatRate(usage))); osInfo.setDisksList(getDisksList()); return osInfo; } @Test void testPlatformEnum() throws Exception { assertThat("Unsupported OS", SystemInfo.getCurrentPlatform(), is(not(PlatformEnum.UNKNOWN))); // Exercise the main method main(null); } public static void main(String[] args) throws Exception { //系统信息 System.out.println("-----------系统信息-----------"); OSInfo osInfo = getSystemInfo(); System.out.println("操作系统:"+ osInfo.getOs()); System.out.println("系统架构:"+ osInfo.getOsArch()); System.out.println("Java版本:"+ osInfo.getJavaVersion()); System.out.println("工作目录:"+ osInfo.getUserDir()); System.out.println("cpu核心数:"+ osInfo.getCpuCount()); System.out.println("主机host:"+ osInfo.getHost()); System.out.println("主机名称:"+ osInfo.getHostName()); String bootTime = osInfo.getBootTime(); // String runTime = ""; // if (StrUtil.isNotEmpty(bootTime)) { // DateTime start = DateUtil.parse(bootTime, DatePattern.NORM_DATETIME_PATTERN); // runTime = DateUtil.formatBetween(start, DateUtil.date()); // } System.out.println("系统正常运行时长:"+ bootTime); //运行时信息 System.out.println("-----------运行时信息-----------"); OSRuntimeInfo osRuntimeInfo = getOSRuntimeInfo(); //1.CPU信息 System.out.println("------cpu信息------"); System.out.println("cpu使用率:" + formatRate(osRuntimeInfo.getCpuUsage())); System.out.println("cpu基准速度:" + osRuntimeInfo.getCpuMaxFreq()); System.out.println("cpu速度:" + osRuntimeInfo.getCpuCurrentFreq()); //2.内存信息 System.out.println("------内存信息------"); //系统内存总量 long total = osRuntimeInfo.getTotalMemory(); long used = osRuntimeInfo.getUsedMemory(); double usage = used * 1.0 / total; System.out.println("系统内存总量:" + total + " -> " + formatData(total)); System.out.println("系统内存使用量:" + used + " -> " + formatData(used)); System.out.println("系统内存使用率:" + formatRate(usage)); //可用虚拟总内存 long swapTotal = osRuntimeInfo.getSwapTotalMemory(); //已用虚拟内存 long swapUsed = osRuntimeInfo.getSwapUsedMemory(); System.out.println("可用虚拟总内存(swap):" + swapTotal + " -> " + formatData(swapTotal)); System.out.println("虚拟内存使用量(swap):" + swapUsed + " -> " + formatData(swapUsed)); //3.磁盘信息 System.out.println("------磁盘信息------"); System.out.println("磁盘读取速度:" + osRuntimeInfo.getDiskReadRate() + "Kb/s"); System.out.println("磁盘写入速度:" + osRuntimeInfo.getDiskWriteRate() + "Kb/s"); List<DisksInfo> disksList = osRuntimeInfo.getDisksList(); for (DisksInfo disksInfo : disksList) { System.out.println("挂载点:" + disksInfo.getDirName()); System.out.println("文件系统名称:" + disksInfo.getSysTypeName()); System.out.println("文件系统类型:" + disksInfo.getTypeName()); System.out.println("磁盘总量:" + disksInfo.getTotal() + " -> " + formatData(disksInfo.getTotal())); System.out.println("磁盘使用量:" + disksInfo.getUsed() + " -> " + formatData(disksInfo.getUsed())); System.out.println("磁盘剩余量:" + disksInfo.getFree() + " -> " + formatData(disksInfo.getFree())); System.out.println("磁盘使用率:" + disksInfo.getUsage()); } //4.网卡网络信息 List<NetworkInfo> netList = getNetworkInfo(); System.out.println("------网卡网络信息------"); for (NetworkInfo networkInfo : netList) { System.out.println("ipv4地址:"+networkInfo.getIpv4Address()); System.out.println("ipv6地址:"+networkInfo.getIpv6Address()); System.out.println("mac地址:"+networkInfo.getMacAddress()); System.out.println("网卡名称:"+networkInfo.getNetworkName()); System.out.println("子网掩码:"+networkInfo.getSubnetMask()); System.out.println("前缀长度:"+networkInfo.getPrefixLength()); System.out.println("首选dns服务器:"+networkInfo.getPreferredDnsServer()); System.out.println("备选dns服务器:"+networkInfo.getAlternateDnsServer()); System.out.println("ipv4默认网关:"+networkInfo.getIpv4Gateway()); System.out.println("ipv6默认网关:"+networkInfo.getIpv6Gateway()); double send = networkInfo.getSend() / 1024.0; double accept = networkInfo.getAccept() / 1024.0; System.out.println("上传速度↑:"+String.format("%.1f%s", send, "Kbps")); System.out.println("下载速度↓:"+String.format("%.1f%s", accept, "Kbps")); System.out.println("======================="); } } /** * @return cpuRate cpu使用率 * @throws InterruptedException */ public static double getCpuRate() throws InterruptedException { CentralProcessor processor = OshiUtil.getHardware().getProcessor(); long[] prevTicks = processor.getSystemCpuLoadTicks(); // 睡眠1s TimeUnit.SECONDS.sleep(1); long[] ticks = processor.getSystemCpuLoadTicks(); long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; double d = 1.0 - (idle * 1.0 / totalCpu); return Double.parseDouble(df.format(d)); } /** * 获取系统启动时间 * * @return */ public static String getBootTime() { String uptime = ""; String os = System.getProperty("os.name").toLowerCase(); try { if (os.contains("win")) { Process uptimeProc = Runtime.getRuntime().exec("net statistics Workstation"); BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream(), Charset.forName("GBK"))); String line; while ((line = in.readLine()) != null) { if (line.startsWith("Statistics since")) { SimpleDateFormat format = new SimpleDateFormat("'Statistics since' yyyy/MM/dd HH:mm:ss"); Date bootTime = format.parse(line); uptime = DateUtil.format(bootTime, DatePattern.NORM_DATETIME_PATTERN); break; } else if (line.startsWith("统计数据开始于")) { SimpleDateFormat format = new SimpleDateFormat("'统计数据开始于' yyyy/MM/dd HH:mm:ss"); Date bootTime = format.parse(line); uptime = DateUtil.format(bootTime, DatePattern.NORM_DATETIME_PATTERN); break; } } } else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) { Process uptimeProc = Runtime.getRuntime().exec("uptime -s"); BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream())); String line = in.readLine(); if (line != null) { uptime = line; } } } catch (Exception e) { log.error("获取系统启动时间异常: {}", e.getMessage()); } return uptime; } /** * 获取磁盘读写速度(Kb/秒) * * @return */ public static Map<String, Double> getDiskIo() { Map<String, Double> map = new HashMap<>(); StringBuilder sb = new StringBuilder(); String os = System.getProperty("os.name").toLowerCase(); try { if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) { Process pos = Runtime.getRuntime().exec("iostat -d 1 2"); pos.waitFor(); InputStreamReader isr = new InputStreamReader(pos.getInputStream()); LineNumberReader lnr = new LineNumberReader(isr); String line; while ((line = lnr.readLine()) != null) { sb.append(line).append("\n"); } } String info = sb.toString(); if (StrUtil.isEmpty(info)) { map.put("diskReadRate", 0D); map.put("diskWriteRate", 0D); return map; } String[] data = info.split("\n"); for (int i = 7; i < data.length; i++) { String[] numdata = data[i].split(" +"); String devName = numdata[0]; double diskReadRate = Double.parseDouble(numdata[2]); //磁盘读数据速率 double diskWriteRate = Double.parseDouble(numdata[3]); //磁盘写数据速率 //这里简单统计,只需要统计一个就行,直接break结束循环 map.put("diskReadRate", diskReadRate); map.put("diskWriteRate", diskWriteRate); break; } } catch (Exception e) { map.put("diskReadRate", 0D); map.put("diskWriteRate", 0D); log.error("获取磁盘传输速度异常: {}", e.getMessage()); } return map; } /** * 格式化输出百分比 * * @param rate 待格式化数据 * *

         *     0.1234   -> 12.34%
         *     1.2      -> 120%
         * 
    * @return */
    public static String formatRate(double rate) { // return new DecimalFormat("#.##%").format(rate); return new DecimalFormat("0.00").format(rate*100); } /** * 格式化输出大小 B/KB/MB... * * @param size 字节大小 * @return */ public static String formatData(long size) { if (size <= 0L) { return "0B"; } else { int digitGroups = Math.min(DataUnit.UNIT_NAMES.length - 1, (int) (Math.log10((double) size) / Math.log10(1024.0D))); return (new DecimalFormat("#,##0.##")).format((double) size / Math.pow(1024.0D, (double) digitGroups)) + " " + DataUnit.UNIT_NAMES[digitGroups]; } } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473
    • 474
    • 475
    • 476
    • 477
    • 478
    • 479
    • 480
    • 481
    • 482
    • 483
    • 484
    • 485
    • 486
    • 487
    • 488
    • 489
    • 490
    • 491
    • 492
    • 493
    • 494
    • 495
    • 496
    • 497
    • 498
    • 499
    • 500
    • 501
    • 502
    • 503
    • 504
    • 505
    • 506
    • 507
    • 508
    • 509
    • 510
    • 511
    • 512
    • 513
    • 514
    • 515
    • 516
    • 517
    • 518
    • 519
    • 520
    • 521
    • 522
    • 523
    • 524
    • 525
    • 526
    • 527
    • 528
    • 529
    • 530
    • 531
    • 532
    • 533
    • 534
    • 535
    • 536
    • 537
    • 538
    • 539
    • 540
    • 541
    • 542
    • 543
    • 544
    • 545
    • 546
    • 547
    • 548
    • 549
    • 550
    • 551
    • 552
    • 553
    • 554
    • 555
    • 556
    • 557
    • 558
    • 559
    • 560
    • 561
    • 562
    • 563
    • 564
    • 565
    • 566
    • 567
    • 568
    • 569
    • 570
    • 571
    • 572
    • 573
    • 574
    • 575
    • 576
    • 577
    • 578
    • 579
    • 580
    • 581
  • 相关阅读:
    腾讯云服务器按量付费如何转为包年包月?
    Facebook对IP都有哪些要求,海外IP代理如何解决的?
    使用JSZip实现在浏览器中操作文件与文件夹
    Windows环境下用python嵌入式环境跑程序可太方便了
    vue 常用开发父子组件的通信
    react-router 源码及原理解析 v5版本
    Echarts 横向滚动和纵向滚动开发
    Java集合-ArrayList源码分析
    前端实现网页转PDF并保存(vue方案)
    c# sqlite 修改字段类型
  • 原文地址:https://blog.csdn.net/weixin_45801664/article/details/129893123