JavaNetty心跳监控

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Properties;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
import org.hyperic.sigar.Who;

public class TestSigar {
    public TestSigar() {
    }

    public static void main(String[] args) {
        try {
            property();
            System.out.println("----------------------------------");
            cpu();
            System.out.println("----------------------------------");
            memory();
            System.out.println("----------------------------------");
            os();
            System.out.println("----------------------------------");
            who();
            System.out.println("----------------------------------");
            file();
            System.out.println("----------------------------------");
            net();
            System.out.println("----------------------------------");
            ethernet();
            System.out.println("----------------------------------");
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    private static void property() throws UnknownHostException {
        Runtime r = Runtime.getRuntime();
        Properties props = System.getProperties();
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        Map<String, String> map = System.getenv();
        String userName = (String)map.get("USERNAME");
        String computerName = (String)map.get("COMPUTERNAME");
        String userDomain = (String)map.get("USERDOMAIN");
        System.out.println("用户名:    " + userName);
        System.out.println("计算机名:    " + computerName);
        System.out.println("计算机域名:    " + userDomain);
        System.out.println("本地ip地址:    " + ip);
        System.out.println("本地主机名:    " + addr.getHostName());
        System.out.println("JVM可以使用的总内存:    " + r.totalMemory());
        System.out.println("JVM可以使用的剩余内存:    " + r.freeMemory());
        System.out.println("JVM可以使用的处理器个数:    " + r.availableProcessors());
        System.out.println("Java的运行环境版本:    " + props.getProperty("java.version"));
        System.out.println("Java的运行环境供应商:    " + props.getProperty("java.vendor"));
        System.out.println("Java供应商的URL:    " + props.getProperty("java.vendor.url"));
        System.out.println("Java的安装路径:    " + props.getProperty("java.home"));
        System.out.println("Java的虚拟机规范版本:    " + props.getProperty("java.vm.specification.version"));
        System.out.println("Java的虚拟机规范供应商:    " + props.getProperty("java.vm.specification.vendor"));
        System.out.println("Java的虚拟机规范名称:    " + props.getProperty("java.vm.specification.name"));
        System.out.println("Java的虚拟机实现版本:    " + props.getProperty("java.vm.version"));
        System.out.println("Java的虚拟机实现供应商:    " + props.getProperty("java.vm.vendor"));
        System.out.println("Java的虚拟机实现名称:    " + props.getProperty("java.vm.name"));
        System.out.println("Java运行时环境规范版本:    " + props.getProperty("java.specification.version"));
        System.out.println("Java运行时环境规范供应商:    " + props.getProperty("java.specification.vender"));
        System.out.println("Java运行时环境规范名称:    " + props.getProperty("java.specification.name"));
        System.out.println("Java的类格式版本号:    " + props.getProperty("java.class.version"));
        System.out.println("Java的类路径:    " + props.getProperty("java.class.path"));
        System.out.println("加载库时搜索的路径列表:    " + props.getProperty("java.library.path"));
        System.out.println("默认的临时文件路径:    " + props.getProperty("java.io.tmpdir"));
        System.out.println("一个或多个扩展目录的路径:    " + props.getProperty("java.ext.dirs"));
        System.out.println("操作系统的名称:    " + props.getProperty("os.name"));
        System.out.println("操作系统的构架:    " + props.getProperty("os.arch"));
        System.out.println("操作系统的版本:    " + props.getProperty("os.version"));
        System.out.println("文件分隔符:    " + props.getProperty("file.separator"));
        System.out.println("路径分隔符:    " + props.getProperty("path.separator"));
        System.out.println("行分隔符:    " + props.getProperty("line.separator"));
        System.out.println("用户的账户名称:    " + props.getProperty("user.name"));
        System.out.println("用户的主目录:    " + props.getProperty("user.home"));
        System.out.println("用户的当前工作目录:    " + props.getProperty("user.dir"));
    }

    private static void memory() throws SigarException {
        Sigar sigar = new Sigar();
        Mem mem = sigar.getMem();
        System.out.println("内存总量:    " + mem.getTotal() / 1024L + "K av");
        System.out.println("当前内存使用量:    " + mem.getUsed() / 1024L + "K used");
        System.out.println("当前内存剩余量:    " + mem.getFree() / 1024L + "K free");
        Swap swap = sigar.getSwap();
        System.out.println("交换区总量:    " + swap.getTotal() / 1024L + "K av");
        System.out.println("当前交换区使用量:    " + swap.getUsed() / 1024L + "K used");
        System.out.println("当前交换区剩余量:    " + swap.getFree() / 1024L + "K free");
    }

    private static void cpu() throws SigarException {
        Sigar sigar = new Sigar();
        CpuInfo[] infos = sigar.getCpuInfoList();
        CpuPerc[] cpuList = null;
        System.out.println("cpu 总量参数情况:" + sigar.getCpu());
        System.out.println("cpu 总百分比情况:" + sigar.getCpuPerc());
        cpuList = sigar.getCpuPercList();

        for(int i = 0; i < infos.length; ++i) {
            CpuInfo info = infos[i];
            System.out.println("第" + (i + 1) + "块CPU信息");
            System.out.println("CPU的总量MHz:    " + info.getMhz());
            System.out.println("CPU生产商:    " + info.getVendor());
            System.out.println("CPU类别:    " + info.getModel());
            System.out.println("CPU缓存数量:    " + info.getCacheSize());
            printCpuPerc(cpuList[i]);
        }

    }

    private static void printCpuPerc(CpuPerc cpu) {
        System.out.println("CPU用户使用率:    " + CpuPerc.format(cpu.getUser()));
        System.out.println("CPU系统使用率:    " + CpuPerc.format(cpu.getSys()));
        System.out.println("CPU当前等待率:    " + CpuPerc.format(cpu.getWait()));
        System.out.println("CPU当前错误率:    " + CpuPerc.format(cpu.getNice()));
        System.out.println("CPU当前空闲率:    " + CpuPerc.format(cpu.getIdle()));
        System.out.println("CPU总的使用率:    " + CpuPerc.format(cpu.getCombined()));
    }

    private static void os() {
        OperatingSystem OS = OperatingSystem.getInstance();
        System.out.println("操作系统:    " + OS.getArch());
        System.out.println("操作系统CpuEndian():    " + OS.getCpuEndian());
        System.out.println("操作系统DataModel():    " + OS.getDataModel());
        System.out.println("操作系统的描述:    " + OS.getDescription());
        System.out.println("操作系统的卖主:    " + OS.getVendor());
        System.out.println("操作系统的卖主名:    " + OS.getVendorCodeName());
        System.out.println("操作系统名称:    " + OS.getVendorName());
        System.out.println("操作系统卖主类型:    " + OS.getVendorVersion());
        System.out.println("操作系统的版本号:    " + OS.getVersion());
    }

    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) {
                Who _who = who[i];
                System.out.println("用户控制台:    " + _who.getDevice());
                System.out.println("用户host:    " + _who.getHost());
                System.out.println("当前系统进程表中的用户名:    " + _who.getUser());
            }
        }

    }

    private static void file() throws Exception {
        Sigar sigar = new Sigar();
        FileSystem[] fslist = sigar.getFileSystemList();
        int i = 0;

        while(i < fslist.length) {
            System.out.println("分区的盘符名称" + i);
            FileSystem fs = fslist[i];
            System.out.println("盘符名称:    " + fs.getDevName());
            System.out.println("盘符路径:    " + fs.getDirName());
            System.out.println("盘符标志:    " + fs.getFlags());
            System.out.println("盘符类型:    " + fs.getSysTypeName());
            System.out.println("盘符类型名:    " + fs.getTypeName());
            System.out.println("盘符文件系统类型:    " + fs.getType());
            FileSystemUsage usage = null;
            usage = sigar.getFileSystemUsage(fs.getDirName());
            switch(fs.getType()) {
            case 2:
                System.out.println(fs.getDevName() + "总大小:    " + usage.getTotal() + "KB");
                System.out.println(fs.getDevName() + "剩余大小:    " + usage.getFree() + "KB");
                System.out.println(fs.getDevName() + "可用大小:    " + usage.getAvail() + "KB");
                System.out.println(fs.getDevName() + "已经使用量:    " + usage.getUsed() + "KB");
                double usePercent = usage.getUsePercent() * 100.0D;
                System.out.println(fs.getDevName() + "资源的利用率:    " + usePercent + "%");
            case 0:
            case 1:
            case 3:
            case 4:
            case 5:
            case 6:
            default:
                System.out.println(fs.getDevName() + "读出:    " + usage.getDiskReads());
                System.out.println(fs.getDevName() + "写入:    " + usage.getDiskWrites());
                ++i;
            }
        }

    }

    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);
            System.out.println("网络设备名:    " + name);
            System.out.println("IP地址:    " + ifconfig.getAddress());
            System.out.println("子网掩码:    " + ifconfig.getNetmask());
            if ((ifconfig.getFlags() & 1L) <= 0L) {
                System.out.println("!IFF_UP...skipping getNetInterfaceStat");
            } else {
                NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
                System.out.println(name + "接收的总包裹数:" + ifstat.getRxPackets());
                System.out.println(name + "发送的总包裹数:" + ifstat.getTxPackets());
                System.out.println(name + "接收到的总字节数:" + ifstat.getRxBytes());
                System.out.println(name + "发送的总字节数:" + ifstat.getTxBytes());
                System.out.println(name + "接收到的错误包数:" + ifstat.getRxErrors());
                System.out.println(name + "发送数据包时的错误数:" + ifstat.getTxErrors());
                System.out.println(name + "接收时丢弃的包数:" + ifstat.getRxDropped());
                System.out.println(name + "发送时丢弃的包数:" + ifstat.getTxDropped());
            }
        }

    }

    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 (!"127.0.0.1".equals(cfg.getAddress()) && (cfg.getFlags() & 8L) == 0L && !"00:00:00:00:00:00".equals(cfg.getHwaddr())) {
                System.out.println(cfg.getName() + "IP地址:" + cfg.getAddress());
                System.out.println(cfg.getName() + "网关广播地址:" + cfg.getBroadcast());
                System.out.println(cfg.getName() + "网卡MAC地址:" + cfg.getHwaddr());
                System.out.println(cfg.getName() + "子网掩码:" + cfg.getNetmask());
                System.out.println(cfg.getName() + "网卡描述信息:" + cfg.getDescription());
                System.out.println(cfg.getName() + "网卡类型" + cfg.getType());
            }
        }

    }
}

  

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

public class ClienHeartBeattHandler extends ChannelHandlerAdapter {
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private ScheduledFuture<?> heartBeat;
    private InetAddress addr;
    private static final String SUCCESS_KEY = "auth_success_key";

    public ClienHeartBeattHandler() {
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.addr = InetAddress.getLocalHost();
        String ip = this.addr.getHostAddress();
        String key = "1234";
        String auth = ip + "," + key;
        ctx.writeAndFlush(auth);
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg instanceof String) {
                String ret = (String)msg;
                if ("auth_success_key".equals(ret)) {
                    this.heartBeat = this.scheduler.scheduleWithFixedDelay(new ClienHeartBeattHandler.HeartBeatTask(ctx), 0L, 2L, TimeUnit.SECONDS);
                    System.out.println(msg);
                } else {
                    System.out.println(msg);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    private class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        public void run() {
            try {
                RequestInfo info = new RequestInfo();
                info.setIp(ClienHeartBeattHandler.this.addr.getHostAddress());
                Sigar sigar = new Sigar();
                CpuPerc cpuPerc = sigar.getCpuPerc();
                HashMap<String, Object> cpuPercMap = new HashMap();
                cpuPercMap.put("combined", cpuPerc.getCombined());
                cpuPercMap.put("user", cpuPerc.getUser());
                cpuPercMap.put("sys", cpuPerc.getSys());
                cpuPercMap.put("wait", cpuPerc.getWait());
                cpuPercMap.put("idle", cpuPerc.getIdle());
                Mem mem = sigar.getMem();
                HashMap<String, Object> memoryMap = new HashMap();
                memoryMap.put("total", mem.getTotal() / 1024L);
                memoryMap.put("used", mem.getUsed() / 1024L);
                memoryMap.put("free", mem.getFree() / 1024L);
                info.setCpuPercMap(cpuPercMap);
                info.setMemoryMap(memoryMap);
                this.ctx.writeAndFlush(info);
            } catch (Exception var7) {
                var7.printStackTrace();
            }

        }

        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            if (ClienHeartBeattHandler.this.heartBeat != null) {
                ClienHeartBeattHandler.this.heartBeat.cancel(true);
                ClienHeartBeattHandler.this.heartBeat = null;
            }

            ctx.fireExceptionCaught(cause);
        }
    }
}

  

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {
    public Client() {
    }

    public static void main(String[] args) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        ((Bootstrap)((Bootstrap)b.group(group)).channel(NioSocketChannel.class)).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingDecoder()});
                sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingEncoder()});
                sc.pipeline().addLast(new ChannelHandler[]{new ClienHeartBeattHandler()});
            }
        });
        ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
        cf.channel().closeFuture().sync();
        group.shutdownGracefully();
    }
}

  

import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

public final class MarshallingCodeCFactory {
    public MarshallingCodeCFactory() {
    }

    public static MarshallingDecoder buildMarshallingDecoder() {
        MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
        MarshallingDecoder decoder = new MarshallingDecoder(provider, 1048576);
        return decoder;
    }

    public static MarshallingEncoder buildMarshallingEncoder() {
        MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
        MarshallingEncoder encoder = new MarshallingEncoder(provider);
        return encoder;
    }
}
import java.io.Serializable;
import java.util.HashMap;

public class RequestInfo implements Serializable {
    private String ip;
    private HashMap<String, Object> cpuPercMap;
    private HashMap<String, Object> memoryMap;

    public RequestInfo() {
    }

    public String getIp() {
        return this.ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public HashMap<String, Object> getCpuPercMap() {
        return this.cpuPercMap;
    }

    public void setCpuPercMap(HashMap<String, Object> cpuPercMap) {
        this.cpuPercMap = cpuPercMap;
    }

    public HashMap<String, Object> getMemoryMap() {
        return this.memoryMap;
    }

    public void setMemoryMap(HashMap<String, Object> memoryMap) {
        this.memoryMap = memoryMap;
    }
}

  

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Server {
    public Server() {
    }

    public static void main(String[] args) throws Exception {
        EventLoopGroup pGroup = new NioEventLoopGroup();
        EventLoopGroup cGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        ((ServerBootstrap)((ServerBootstrap)((ServerBootstrap)b.group(pGroup, cGroup).channel(NioServerSocketChannel.class)).option(ChannelOption.SO_BACKLOG, 1024)).handler(new LoggingHandler(LogLevel.INFO))).childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingDecoder()});
                sc.pipeline().addLast(new ChannelHandler[]{MarshallingCodeCFactory.buildMarshallingEncoder()});
                sc.pipeline().addLast(new ChannelHandler[]{new ServerHeartBeatHandler()});
            }
        });
        ChannelFuture cf = b.bind(8765).sync();
        cf.channel().closeFuture().sync();
        pGroup.shutdownGracefully();
        cGroup.shutdownGracefully();
    }
}

  

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import java.util.HashMap;

public class ServerHeartBeatHandler extends ChannelHandlerAdapter {
    private static HashMap<String, String> AUTH_IP_MAP = new HashMap();
    private static final String SUCCESS_KEY = "auth_success_key";

    static {
        AUTH_IP_MAP.put("192.168.1.200", "1234");
    }

    public ServerHeartBeatHandler() {
    }

    private boolean auth(ChannelHandlerContext ctx, Object msg) {
        String[] ret = ((String)msg).split(",");
        String auth = (String)AUTH_IP_MAP.get(ret[0]);
        if (auth != null && auth.equals(ret[1])) {
            ctx.writeAndFlush("auth_success_key");
            return true;
        } else {
            ctx.writeAndFlush("auth failure !").addListener(ChannelFutureListener.CLOSE);
            return false;
        }
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String) {
            this.auth(ctx, msg);
        } else if (msg instanceof RequestInfo) {
            RequestInfo info = (RequestInfo)msg;
            System.out.println("--------------------------------------------");
            System.out.println("当前主机ip为: " + info.getIp());
            System.out.println("当前主机cpu情况: ");
            HashMap<String, Object> cpu = info.getCpuPercMap();
            System.out.println("总使用率: " + cpu.get("combined"));
            System.out.println("用户使用率: " + cpu.get("user"));
            System.out.println("系统使用率: " + cpu.get("sys"));
            System.out.println("等待率: " + cpu.get("wait"));
            System.out.println("空闲率: " + cpu.get("idle"));
            System.out.println("当前主机memory情况: ");
            HashMap<String, Object> memory = info.getMemoryMap();
            System.out.println("内存总量: " + memory.get("total"));
            System.out.println("当前内存使用量: " + memory.get("used"));
            System.out.println("当前内存剩余量: " + memory.get("free"));
            System.out.println("--------------------------------------------");
            ctx.writeAndFlush("info received!");
        } else {
            ctx.writeAndFlush("connect failure!").addListener(ChannelFutureListener.CLOSE);
        }

    }
}

  

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestTimeJob {
    public TestTimeJob() {
    }

    public static void main(String[] args) throws Exception {
        Temp command = new Temp();
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleWithFixedDelay(command, 2L, 3L, TimeUnit.SECONDS);
    }
}

  

  

原文地址:https://www.cnblogs.com/sunliyuan/p/10969409.html