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);
    }
}

 

相關文章
相關標籤/搜索