互联网技术23——心跳检查及sigar的使用示例

心跳检测示例中需要结合sigar,所以这里先演示一下sigar的使用。

1.首先要下载sigar包,导入包或使用maven依赖导入

2.这点一定要注意,Sigar工具类下载地址需要将相应系统的DLL库放入jdk或jre的bin目录下才可以正常使用

  • Windows下配置:根据自己的操作系统版本选择sigar-amd64-winnt.dll或sigar-x86-winnt.dll拷贝到C:\Windows\System32中

  • Linux下配置:将libsigar-amd64-linux.so或libsigar-x86-linux.so拷贝到/usr/lib64或/lib64或/lib或/usr/lib目录下,如果不起作用,还需要sudochmod 744修改libsigar-amd64-linux.so文件权限

演示代码:

package com.sigarTest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Properties;

import org.hyperic.sigar.Cpu;
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.NetFlags;
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 static void main(String[] args) {
        try {
            // System信息,从jvm获取
            property();
            System.out.println("----------------------------------");
            // cpu信息
            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 e1) {
            e1.printStackTrace();
        }
    }

    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");// 获取用户名
        String computerName = map.get("COMPUTERNAME");// 获取计算机名
        String userDomain = 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++) {// 不管是单块CPU还是多CPU都适用
            CpuInfo info = infos[i];
            System.out.println("第" + (i + 1) + "块CPU信息");
            System.out.println("CPU的总量MHz:    " + info.getMhz());// CPU的总量MHz
            System.out.println("CPU生产商:    " + info.getVendor());// 获得CPU的卖主,如:Intel
            System.out.println("CPU类别:    " + info.getModel());// 获得CPU的类别,如:Celeron
            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();
        // 操作系统内核类型如: 386、486、586等x86
        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.getName():    " + OS.getName());
        // System.out.println("OS.getPatchLevel():    " + OS.getPatchLevel());//
        // 操作系统的卖主
        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++) {
                // System.out.println("当前系统进程表中的用户名" + String.valueOf(i));
                Who _who = who[i];
                System.out.println("用户控制台:    " + _who.getDevice());
                System.out.println("用户host:    " + _who.getHost());
                // System.out.println("getTime():    " + _who.getTime());
                // 当前系统进程表中的用户名
                System.out.println("当前系统进程表中的用户名:    " + _who.getUser());
            }
        }
    }

    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("分区的盘符名称" + i);
            FileSystem fs = fslist[i];
            // 分区的盘符名称
            System.out.println("盘符名称:    " + fs.getDevName());
            // 分区的盘符名称
            System.out.println("盘符路径:    " + fs.getDirName());
            System.out.println("盘符标志:    " + fs.getFlags());//
            // 文件系统类型,比如 FAT32、NTFS
            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 0: // TYPE_UNKNOWN :未知
                break;
            case 1: // TYPE_NONE
                break;
            case 2: // TYPE_LOCAL_DISK : 本地硬盘
                // 文件系统总大小
                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() * 100D;
                // 文件系统资源的利用率
                System.out.println(fs.getDevName() + "资源的利用率:    " + usePercent + "%");
                break;
            case 3:// TYPE_NETWORK :网络
                break;
            case 4:// TYPE_RAM_DISK :闪存
                break;
            case 5:// TYPE_CDROM :光驱
                break;
            case 6:// TYPE_SWAP :页面交换
                break;
            }
            System.out.println(fs.getDevName() + "读出:    " + usage.getDiskReads());
            System.out.println(fs.getDevName() + "写入:    " + usage.getDiskWrites());
        }
        return;
    }

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

 

心跳检测

在使用socket时一般会处理多个服务器之间的心跳检测,一般来讲,我们去维护服务集群,肯定又一个或几台服务器主机(Maser),然后还应该有n台服务器从机(Slave),那么我们的主机肯定要时时刻刻知道自己下面的从服务器的各个方面情况,然后进行实时监控的功能,这个在分布式架构里叫做心跳检测或者说心跳监控,最佳处理方案我们实施决定是使用一些通信架构来实现,Netty就可以去做这样一件事。

AuthReques

package com.nettyHeart;

import java.io.Serializable;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class AuthRequest implements Serializable{

    private static final long serialVersionUID = 1862080046425754797L;
    private String auth;

    public AuthRequest(String auth) {
        this.auth = auth;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }
}

 

AuthResponse

package com.nettyHeart;

import java.io.Serializable;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class AuthRequest implements Serializable{

    private static final long serialVersionUID = 1862080046425754797L;
    private String auth;

    public AuthRequest(String auth) {
        this.auth = auth;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }
}

Error

package com.nettyHeart;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class Error {
    private String error;
    public Error(String error) {
        this.error = error;
    }
    public String getError() {
        return error;
    }



    public void setError(String error) {
        this.error = error;
    }
}

HeartRequest

package com.nettyHeart;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class HeartRequest implements Serializable{

    private static final long serialVersionUID = -6839771181547020216L;
    private String ip;
    private Map<String,Object> cupMap;
    private Map<String,Object> memoryMap;

    public String getIp() {
        return ip;
    }

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

    public Map<String, Object> getCupMap() {
        return cupMap;
    }

    public void setCupMap(Map<String, Object> cupMap) {
        this.cupMap = cupMap;
    }

    public Map<String, Object> getMemoryMap() {
        return memoryMap;
    }

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

HeartResponse

package com.nettyHeart;

import java.io.Serializable;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class HeartResponse implements Serializable{

    private static final long serialVersionUID = -702866278650479762L;
    private String msg;

    public HeartResponse(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

MarshallingCodeCFactory

package com.nettyHeart;

import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

public final class MarshallingCodeCFactory {

    /**
     * 创建Jboss Marshalling解码器MarshallingDecoder
     */
    public static MarshallingDecoder buildMarshallingDecoder() {
        //首先通过Marshalling工具类的getProvidedMarshallerFactory静态方法获取MarshallerFactory实例
        //参数“serial”表示创建的是Java序列化工厂对象,它由jboss-marshalling-serial-1.3.0.CR9.jar提供。
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        //创建了MarshallingConfiguration对象
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        //将它的版本号设置为5
        configuration.setVersion(5);
        //然后根据MarshallerFactory和MarshallingConfiguration创建UnmarshallerProvider实例
        UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);
        //最后通过构造函数创建Netty的MarshallingDecoder对象
        //它有两个参数,分别是UnmarshallerProvider和单个消息序列化后的最大长度。
        MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
        return decoder;
    }

    /**
     * 创建Jboss Marshalling编码器MarshallingEncoder
     */
    public static MarshallingEncoder buildMarshallingEncoder() {
        final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");
        final MarshallingConfiguration configuration = new MarshallingConfiguration();
        configuration.setVersion(5);
        //创建MarshallerProvider对象,它用于创建Netty提供的MarshallingEncoder实例
        MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);
        //MarshallingEncoder用于将实现序列化接口的POJO对象序列化为二进制数组。
        MarshallingEncoder encoder = new MarshallingEncoder(provider);
        return encoder;
    }
}

MasterServer

package com.nettyHeart;

import com.nettyMarshalling.MarshallingCodeFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
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;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class MasterServer {
    public void init (int port){
        //用于接收网络连接
        EventLoopGroup bootGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bootGroup,workGroup);
        bootstrap.channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                        socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecode());
                        socketChannel.pipeline().addLast(new ServerHandler());
                    }
                });
        try {
            ChannelFuture cf = bootstrap.bind(8765).sync();
            cf.channel().closeFuture().sync();
            bootGroup.shutdownGracefully();
            workGroup.shutdownGracefully();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MasterServer ms = new MasterServer();
        ms.init(8765);
    }
}

ServerHandler

package com.nettyHeart;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class ServerHandler extends ChannelHandlerAdapter{
    private static final String SUCCESS_KEY = "auth_success_key";
    private static final String FAILURE_KEY = "auth_failure_key";

    //存放从机信息的列表map
    private static Map<String,String> AUTH_IP_MAP = new HashMap<>();
    static {
        AUTH_IP_MAP.put("192.168.156.1","1234");
    }

    private boolean auth(ChannelHandlerContext chx, Object msg){
        String[] ret = ((AuthRequest)msg).getAuth().split(":");
        String auth =AUTH_IP_MAP.get(ret[0]);
        if(auth != null && auth.equals(ret[1])){
            chx.writeAndFlush(new AuthResponse(SUCCESS_KEY));
            return true;
        }else {
            chx.writeAndFlush(new AuthResponse(FAILURE_KEY));
            return false;
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("master read....");
        System.out.println(msg instanceof AuthRequest);
        if(msg instanceof AuthRequest){
            this.auth(ctx,msg);
        }else if(msg instanceof HeartRequest){
            HeartRequest req = (HeartRequest) msg;
            System.out.println("--------------------------------------");
            System.out.println("当前主机ip为:"+req.getIp());
            System.out.println("当前主机cpu情况:");
            Map cpu = req.getCupMap();
            System.out.println("总使用率:"+cpu.get("combind"));
            System.out.println("用户使用率:"+cpu.get("user"));
            System.out.println("系统使用率:"+cpu.get("sys"));
            System.out.println("等待率:"+cpu.get("wait"));
            System.out.println("空闲率:"+cpu.get("idle"));

            Map memory = req.getMemoryMap();
            System.out.println("内存总量:"+memory.get("total"));
            System.out.println("用户使用率:"+memory.get("used"));
            System.out.println("系统使用率:"+memory.get("free"));
            System.out.println("-----------------------------------");

            ctx.writeAndFlush(new HeartResponse("info received"));

        }else {
            ctx.writeAndFlush(new Error("connect failure")).addListener(ChannelFutureListener.CLOSE);
        }
    }
}

SlaveClient

package com.nettyHeart;

import com.nettyMarshalling.MarshallingCodeFactory;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
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;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class SlaveClient {
    private void init (String ip, int port){
        EventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workGroup);
        bootstrap.channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingEncoder());
                        socketChannel.pipeline().addLast(MarshallingCodeFactory.buildMarshallingDecode());
                        socketChannel.pipeline().addLast(new SlaveClientHeartBeat());
                    }
                });
        try {
            ChannelFuture cf = bootstrap.connect(ip,port).sync();
            System.out.println("Slave Client started. IP : " + ip + ":" + port);
            cf.channel().closeFuture().sync();
            workGroup.shutdownGracefully();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SlaveClient sc =new SlaveClient();
        sc.init("127.0.0.1",8765);
    }
}

SlaveClientHeartBeat

package com.nettyHeart;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by BaiTianShi on 2018/9/13.
 */
public class SlaveClientHeartBeat extends ChannelHandlerAdapter {
    private ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);

    private ScheduledFuture<?> heartBeat;

    private InetAddress address;

    private static final String SUCCESS_KEY = "auth_success_key";
    private static final String FAILURE_KEY = "auth_failure_key";

    /**
     * 当连接建立激活时调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("auth start...");
        address = InetAddress.getLocalHost();
        String ip = address.getHostAddress();
        System.out.println(ip);
        String key = "1234";
        //模拟证书与主机进行认证, 真实环境中此处应该进行加密处理
        ctx.writeAndFlush(new AuthRequest(ip + ":" + key));
    }



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        try{
            if((msg instanceof AuthResponse)){
                AuthResponse ret = (AuthResponse)msg;
                if( SUCCESS_KEY.equals(ret.getResult()) ){
                    //定时任务,每隔5秒钟执行一次HeartBeatTask, 延迟0秒开始
                    this.heartBeat = this.scheduled.scheduleWithFixedDelay(new HeartBeatTask(ctx), 0, 5, TimeUnit.SECONDS);
                    System.out.println(ret.getResult());
                }else if(FAILURE_KEY.equals(ret.getResult())){
                    System.out.println("权限认证失败。");
                }
            }else if((msg instanceof HeartResponse)){
                HeartResponse ret = (HeartResponse)msg;
                System.out.println(ret.getMsg());
            }else if((msg instanceof Error)){
                Error ret = (Error) msg;
                System.out.println(ret.getError());
            }else{
                System.out.println(msg);
            }
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }finally{
            ReferenceCountUtil.release(msg);
        }

    }


    public class HeartBeatTask implements Runnable{

        private final ChannelHandlerContext ctx;

        public HeartBeatTask(ChannelHandlerContext ctx) {
            // TODO Auto-generated constructor stub
            this.ctx = ctx;
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                HeartRequest requestInfo = new HeartRequest();
                requestInfo.setIp(address.getHostAddress());
                //Sigar工具类,用来获取当前系统的CPU内存等等信息,下面有详细使用介绍
                Sigar sigar = new Sigar();

                CpuPerc cpuPerc = sigar.getCpuPerc();
                Map<String, Object> cpuMap = new HashMap<>();
                cpuMap.put("combined", cpuPerc.getCombined());
                cpuMap.put("user", cpuPerc.getUser());
                cpuMap.put("sys", cpuPerc.getSys());
                cpuMap.put("wait", cpuPerc.getWait());
                cpuMap.put("idle", cpuPerc.getIdle());
                requestInfo.setCupMap(cpuMap);

                Mem memPerc = sigar.getMem();
                Map<String, Object> memMap = new HashMap<String, Object>();
                memMap.put("total", memPerc.getTotal() / 1024L);
                memMap.put("used", memPerc.getUsed() / 1024L);
                memMap.put("free", memPerc.getFree() / 1024L);
                requestInfo.setMemoryMap(memMap);

                ctx.writeAndFlush(requestInfo);

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值