netty实用场景-心跳检测(java)

netty主要应用场景心跳检测和网络通信,下面主要介绍心跳检测内容,主要分服务端和客户端两部分。

1、服务端,接收并解析客户端信息,判断客户端是否还活着

EventLoopGroup pGroup = new NioEventLoopGroup();
EventLoopGroup cGroup = new NioEventLoopGroup();

ServerBootstrap b = new ServerBootstrap();
b.group(pGroup, cGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
//设置日志
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//Jboss Marshalling解码器MarshallingDecoder和MarshallingEncoder
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
      sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
      sc.pipeline().addLast(new ServerHeartBeatHandler());
   }
});

ChannelFuture cf = b.bind(8888).sync();

cf.channel().closeFuture().sync();
pGroup.shutdownGracefully();
cGroup.shutdownGracefully();

2、客户端,发送本服务器运行信息,内存、CPU等

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel sc) throws Exception {
//Jboss Marshalling解码器MarshallingDecoder和MarshallingEncoder
sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());
      sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());
      sc.pipeline().addLast(new ClienHeartBeattHandler());
   }
});

ChannelFuture cf = b.connect("127.0.0.1", 8888).sync();

cf.channel().closeFuture().sync();
group.shutdownGracefully();

3、检查心跳连接,判断一个机器是否或者,需要获取计算机当时运行状态。

sigar.jar包获取,根据本机电脑配置,选择sigar的环境信息,例如我的电脑,window 64位:sigar-amd64-winnt.dll

获取cup信息代码如下:

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

4、总结:

使用netty进行心跳检测,主要基于netty的网络通信功能,客户端往服务端发送本服务运行信息(内存、CPU),服务端接受客户端消息,获取服客户端服务器运行情况,根据获取服务器参数检查客户端是否可用。

猜你喜欢

转载自gongzhibo0509.iteye.com/blog/2412137