java obtains server cpu, memory and other data through sigar

Posted by sfarid on Mon, 20 Jan 2020 17:18:10 +0100

First, introduce the sigar package

implementation 'org.fusesource:sigar:1.6.4'

Secondly,

Under windows environment, put the three files of sign-amd64-winnt.dll, sign-x86-winnt.dll and sign-x86-winnt.lib in the bin directory of jdk

Or configuration under Windows: select sign-amd64-winnt.dll or sign-x86-winnt.dll to copy to C:\Windows\System32 according to your own operating system version

Configuration under Linux: copy the sigar-amd64-linux.so or libsigar-x86-linux.so under the Lib package to the directory / usr/lib64 or / lib64 or / lib or / usr/lib. If it doesn't work, sudohmod 744 is also required to modify the file permission of libsigar-amd64-linux.so

Finally, it's code

import com.boran.demonstration.config.BaseController;
import com.boran.demonstration.config.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hyperic.sigar.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zp.wei
 * @DATE: 2020/1/19 15:18
 */
@CrossOrigin
@RestController
public class ComputerInformationController {


    /**
     * View computer information
     * 1,Introducing the sigar.jar package
     * 2,windows Under the environment, put the three files of sign-amd64-winnt.dll, sign-x86-winnt.dll and sign-x86-winnt.lib into the bin directory of jdk
     *
     * @return
     */
    @ApiOperation("View computer information")
    @GetMapping("/information")
    public Result ComputerInformation() {
        Map<String, Object> all = new HashMap<>();
        try {
            // Memory information
            Map<String, String> memory = getMemory();
            all.put("memory", memory);
            System.out.println("----------------------------------");
            // cpu Information
            List<Object> cpu = getCpu();
            all.put("cpu", cpu);
            System.out.println("----------------------------------");
            // file system information
//            file();
//            System.out.println("----------------------------------");
            // network information
//            net();
//            System.out.println("----------------------------------");
            // System information, getting from the jvm
//            property();
//            System.out.println("----------------------------------");
            // Operating system information
//            os();
//            System.out.println("----------------------------------");
            // User information
//            who();
//            System.out.println("----------------------------------");
            // Ethernet information
//            ethernet();
//            System.out.println("----------------------------------");
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        return Result.ok(all);
    }


    /**
     * Memory
     *
     * @throws SigarException
     */
    private Map<String, String> getMemory() throws SigarException {
        Sigar sigar = new Sigar();
        Mem mem = sigar.getMem();
        Swap swap = sigar.getSwap();
        Map<String, String> map = new HashMap<>(16);
        map.put("memTotal", mem.getTotal() / 1024L + "K av");
        map.put("memUsed", mem.getUsed() / 1024L + "K used");
        map.put("memFree", mem.getFree() / 1024L + "K free");
        map.put("swapTotal", swap.getTotal() / 1024L + "K av");
        map.put("swapUsed", swap.getUsed() / 1024L + "K used");
        map.put("swapFree", swap.getFree() / 1024L + "K free");
        return map;
    }


    /**
     * cpu
     *
     * @throws SigarException
     */
    private List getCpu() throws SigarException {
        Sigar sigar = new Sigar();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuList[] = sigar.getCpuPercList();
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < infos.length; i++) {// Both single CPU and multi CPU are applicable
            CpuInfo info = infos[i];
            Map<String, Object> map = new HashMap<>(16);
            map.put("number", i + 1);
            map.put("getMhz", info.getMhz());
            map.put("getVendor", info.getVendor());
            map.put("getModel", info.getModel());
            map.put("getCacheSize", info.getCacheSize());
            map.put("getUser", CpuPerc.format(cpuList[i].getUser()));
            map.put("getSys", CpuPerc.format(cpuList[i].getSys()));
            map.put("getWait", CpuPerc.format(cpuList[i].getWait()));
            map.put("getNice", CpuPerc.format(cpuList[i].getNice()));
            map.put("getIdle", CpuPerc.format(cpuList[i].getIdle()));
            map.put("getCombined", CpuPerc.format(cpuList[i].getCombined()));
            list.add(map);
        }
        return list;
    }


    /**
     * file system information
     *
     * @throws Exception
     */
    /*private static void file() throws Exception {
        Sigar sigar = new Sigar();
        FileSystem fslist[] = sigar.getFileSystemList();
        for (int i = 0; i < fslist.length; i++) {
            System.out.println("The drive letter name of the partition "+ I";
            FileSystem fs = fslist[i];
            // Drive letter name of the partition
            System.out.println("Drive name: '+ fs.getDevName());
            // Drive letter name of the partition
            System.out.println("Drive path: '+ fs.getDirName());
            System.out.println("Drive flag: "+ fs.getFlags())//
            // File system type, such as FAT32, NTFS
            System.out.println("Drive type: '+ fs.getSysTypeName());
            // File system type name, such as local hard disk, optical drive, network file system, etc
            System.out.println("Drive type name: '+ fs.getTypeName());
            // file system type
            System.out.println("Drive letter file system type: '+ fs.getType());
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            switch (fs.getType()) {
                case 0: // TYPE_UNKNOWN : Unknown
                    break;
                case 1: // TYPE_NONE
                    break;
                case 2: // TYPE_LOCAL_DISK : Local hard disk
                    // Total file system size
                    System.out.println(fs.getDevName() + "Total size: "+ usage. Gettotal() +" KB ");
                    // File system remaining size
                    System.out.println(fs.getDevName() + "Remaining size: "+ usage. Getfree() +" KB ");
                    // File system available size
                    System.out.println(fs.getDevName() + "Available size: "+ usage. Getavail() +" KB ");
                    // File system used
                    System.out.println(fs.getDevName() + "Used amount: "+ usage. Getused() +" KB ");
                    double usePercent = usage.getUsePercent() * 100D;
                    // Utilization of file system resources
                    System.out.println(fs.getDevName() + "Resource utilization rate: "+ usePercent +"% ");
                    break;
                case 3:// TYPE_NETWORK : network
                    break;
                case 4:// TYPE_RAM_DISK : Flash Memory
                    break;
                case 5:// TYPE_CDROM : CD drive
                    break;
                case 6:// TYPE_SWAP : Page exchange
                    break;
            }
            System.out.println(fs.getDevName() + "Read out: "+ usage.getDiskReads());
            System.out.println(fs.getDevName() + "Write: "+ usage.getDiskWrites());
        }
        return;
    }*/


    /**
     * network information
     *
     * @throws Exception
     */
    /*private static void net() throws Exception {
        Sigar sigar = new Sigar();
        String ifNames[] = sigar.getNetInterfaceList();
        for (int i = 0; i < ifNames.length; i++) {
            String name = ifNames[i];
            NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
            if ((ifconfig.getFlags() & 1L) <= 0L) {
                System.out.println("!IFF_UP...skipping getNetInterfaceStat");
                continue;
            }
            NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
            System.out.println(name + "Received packages: "+ ifstat.getRxPackets()); / / received packages
            System.out.println(name + "Packages sent: "+ ifstat.getTxPackets()); / / packages sent
            System.out.println(name + "Total bytes received: "+ ifstat.getRxBytes()); / / total bytes received
            System.out.println(name + "Total bytes sent: '+ ifstat.getTxBytes()); / / total bytes sent
            System.out.println(name + "Number of error packets received: '+ ifstat.getRxErrors()); / / number of error packets received
            System.out.println(name + "Number of errors in sending packets: '+ ifstat.getTxErrors()); / / number of errors in sending packets
            System.out.println(name + "Number of packets dropped on receive: '+ ifstat.getRxDropped()); / / number of packets dropped on receive
            System.out.println(name + "Number of packets dropped when sending: "+ ifstat.getTxDropped()); / / number of packets dropped when sending
        }
    }*/


    /**
     * System Information, getting from the jvm
     *
     * @throws UnknownHostException
     */
    /*private static void property() throws UnknownHostException {
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        InetAddress addr;
        addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        Map<String, String> map = System.getenv();
        String userName = map.get("USERNAME");// Get user name
        String computerName = map.get("COMPUTERNAME");// Get computer name
        String userDomain = map.get("USERDOMAIN");// Get computer domain name
        System.out.println("User name: "+ userName);
        System.out.println("Computer name: "+ computerName);
        System.out.println("Computer domain name: "+ userdomain";
        System.out.println("Local ip address: "+ ip";
        System.out.println("Local host name: "+ addr.getHostName());
        System.out.println("JVM Total memory available: "+ r.totalMemory());
        System.out.println("JVM Remaining memory available: "+ r.freeMemory());
        System.out.println("JVM Number of processors available: '+ r.availableProcessors());
        System.out.println("Java Running environment version of: "+ props.getProperty("java.version ");
        System.out.println("Java Running environment provider of: "+ props.getProperty("java.vendor "));
        System.out.println("Java Supplier URL: "+ props.getProperty("java.vendor.url ");
        System.out.println("Java Installation path of: "+ props.getProperty("java.home ");
        System.out.println("Java Virtual machine specification version of: "+ props.getProperty("java.vm.specification.version ");
        System.out.println("Java Virtual machine specification vendor for: "+ props.getProperty("java.vm.specification.vendor "));
        System.out.println("Java Virtual machine specification name of: "+ props.getProperty("java.vm.specification.name ");
        System.out.println("Java Virtual machine implementation version of: "+ props.getProperty("java.vm.version ");
        System.out.println("Java "+ props.getProperty("java.vm.vendor ");
        System.out.println("Java Virtual machine implementation name of: "+ props.getProperty("java.vm.name "));
        System.out.println("Java Runtime environment specification version: "+ props.getProperty("java.specification.version ");
        System.out.println("Java Runtime environment specification vendor: "+ props.getProperty("java.specification.vender ");
        System.out.println("Java Runtime environment specification Name: "+ props.getProperty("java.specification.name ");
        System.out.println("Java Class format version number of: "+ props.getProperty("java.class.version ");
        System.out.println("Java Class path of: "+ props.getProperty("java.class.path ");
        System.out.println("List of paths to search when loading libraries: "+ props.getProperty("java.library.path "));
        System.out.println("Default temporary file path: "+ props.getProperty("java.io.tmpdir ");
        System.out.println("The path of one or more extension directories: "+ props.getProperty("java.ext.dirs ");
        System.out.println("Name of the operating system: "+ props.getProperty("os.name "));
        System.out.println("Architecture of the operating system: "+ props.getProperty("os.arch ");
        System.out.println("Version of the operating system: '+ props. Getproperty ('os. Version');
        System.out.println("File separator: '+ props. Getproperty ('File. Separator');
        System.out.println("Path separator: "+ props.getProperty("path.separator ");
        System.out.println("Line separator: "+ props.getProperty("line.separator ");
        System.out.println("User's account name: "+ props.getProperty("user.name "));
        System.out.println("User's home directory: "+ props.getProperty("user.home ");
        System.out.println("Current working directory of the user: "+ props.getProperty("user.dir ");
    }*/


    /**
     * Operating system information
     *
     * @throws SigarException
     */
    /*private static void os() {
        OperatingSystem OS = OperatingSystem.getInstance();
        // Operating system kernel types such as 386, 486, 586, etc
        System.out.println("Operating system: "+ OS.getArch());
        System.out.println("Operating system cpuendian(): "+ OS. Getcpuendian())//
        System.out.println("Operating system datamodel(): "+ OS. Getdatamodel())//
        // System description
        System.out.println("Description of the operating system: "+ OS.getDescription());
        // Operating system type
        // System.out.println("OS.getName():    " + OS.getName());
        // System.out.println("OS.getPatchLevel():    " + OS.getPatchLevel());//
        // Vendor of operating system
        System.out.println("Vendor of operating system: "+ OS.getVendor());
        // Seller name
        System.out.println("The vendor name of the operating system: "+ OS.getVendorCodeName());
        // Operating system name
        System.out.println("Operating system name: "+ OS.getVendorName());
        // Operating system vendor type
        System.out.println("Operating system vendor type: "+ OS.getVendorVersion());
        // Version number of the operating system
        System.out.println("Version number of the operating system: "+ OS.getVersion());
    }*/


    /**
     * User information
     *
     * @throws SigarException
     */
    /*private static void who() throws SigarException {
        Sigar sigar = new Sigar();
        Who who[] = sigar.getWhoList();
        if (who != null && who.length > 0) {
            for (int i = 0; i < who.length; i++) {
                // System.out.println("User name in the current system process table "+ String.valueOf(i));
                Who _who = who[i];
                System.out.println("User console: "+ _who.getDevice());
                System.out.println("User host: "+ _who. Gethost());
                // System.out.println("getTime():    " + _who.getTime());
                // User name in the current system process table
                System.out.println("User name in the current system process table: "+ _who.getUser());
            }
        }
    }*/


    /**
     * Ethernet information
     *
     * @throws SigarException
     */
    /*private static void ethernet() throws SigarException {
        Sigar sigar = null;
        sigar = new Sigar();
        String[] ifaces = sigar.getNetInterfaceList();
        for (int i = 0; i < ifaces.length; i++) {
            NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
            if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
                    || NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
                continue;
            }
            System.out.println(cfg.getName() + "IP Address: "+ cfg.getAddress());// IP address
            System.out.println(cfg.getName() + "Gateway broadcast address: "+ cfg.getBroadcast()); / / gateway broadcast address
            System.out.println(cfg.getName() + "MAC address of network card: "+ cfg.getHwaddr()); / / MAC address of network card
            System.out.println(cfg.getName() + "Subnet mask: '+ cfg.getNetmask()); / / subnet mask
            System.out.println(cfg.getName() + "Network card description information: "+ cfg.getDescription()); / / network card description information
            System.out.println(cfg.getName() + "Network card type "+ cfg.getType())//
        }
    }*/

}

Finally, basically all the server information you want is available... The above code hasn't been written, which is not a big problem. It can still be used

Published 24 original articles, won praise 26, visited 5228
Private letter follow

Topics: Java network jvm Windows