(socket-nio-netty学习-2)Netty基础入门

来源:互联网 发布:数据库的主要特点是 编辑:程序博客网 时间:2024/06/04 19:36
原文  http://blog.csdn.net/haoyuyang/article/details/53243785

1.为什么选择Netty

上一篇文章我们已经了解了Socket通信(IO/NIO/AIO)编程,对于通信模型已经有了一个基本的认识。其实上一篇文章中,我们学习的仅仅是一个模型,如果想把这些真正的用于实际工作中,那么还需要不断的完善、扩展和优化。比如经典的TCP读包写包问题,或者是数据接收的大小,实际的通信处理与应答的处理逻辑等等一些细节问题需要认真的去思考,而这些都需要大量的时间和经历,以及丰富的经验。所以想学好Socket通信不是件容易事,那么接下来就来学习一下新的技术Netty,为什么会选择Netty?因为它简单!使用Netty不必编写复杂的逻辑代码去实现通信,再也不需要去考虑性能问题,不需要考虑编码问题,半包读写等问题。强大的Netty已经帮我们实现好了,我们只需要使用即可。

Netty是最流行的NIO框架,它的健壮性、功能、性能、可定制性和可扩展性在同类框架都是首屈一指的。它已经得到成百上千的商业/商用项目验证,如Hadoop的RPC框架Avro、RocketMQ以及主流的分布式通信框架Dubbox等等。

2.Netty简介

Netty是基于Java NIO client-server的网络应用框架,使用Netty可以快速开发网络应用,例如服务器和客户端协议。Netty提供了一种新的方式来开发网络应用程序,这种新的方式使它很容易使用和具有很强的扩展性。Netty的内部实现是很复杂的,但是Netty提供了简单易用的API从网络处理代码中解耦业务逻辑。Netty是完全基于NIO实现的,所以整个Netty都是异步的。

网络应用程序通常需要有较高的可扩展性,无论是Netty还是其他的基于Java Nio的框架,都会提供可扩展性的解决方案。Netty中一个关键组成部分是它的异步特性,本片文章将讨论同步(阻塞)和异步(非阻塞)的IO来说明为什么使用异步代码解决扩展性问题以及如何使用异步。

3.Netty架构组成(借用一下网上的图片)


Netty实现原理浅析,写的很不错,感兴趣的可以看一下。

4.Helloworld入门

在学习Netty之前,先来回顾一下NIO的通信步骤:

①创建ServerSocketChannel,为其配置非阻塞模式。

②绑定监听,配置TCP参数,录入backlog大小等。

③创建一个独立的IO线程,用于轮询多路复用器Selector。

④创建Selector,将之前创建的ServerSocketChannel注册到Selector上,并设置监听标识位SelectionKey.OP_ACCEPT。

⑤启动IO线程,在循环体中执行Selector.select()方法,轮询就绪的通道。

⑥当轮询到处于就绪状态的通道时,需要进行操作位判断,如果是ACCEPT状态,说明是新的客户端接入,则调用accept方法接收新的客户端。

⑦设置新接入客户端的一些参数,如非阻塞,并将其继续注册到Selector上,设置监听标识位等。

⑧如果轮询的通道标识位是READ,则进行读取,构造Buffer对象等。

⑨更细节的问题还有数据没发送完成继续发送的问题......

好啦,开始学习Netty了。先去http://netty.io/上下载所有的Netty包。

Netty通信的步骤:

①创建两个NIO线程组,一个专门用于网络事件处理(接受客户端的连接),另一个则进行网络通信的读写。

②创建一个ServerBootstrap对象,配置Netty的一系列参数,例如接受传出数据的缓存大小等。

③创建一个用于实际处理数据的类ChannelInitializer,进行初始化的准备工作,比如设置接受传出数据的字符集、格式以及实际处理数据的接口。

④绑定端口,执行同步阻塞方法等待服务器端启动即可。

强烈推荐读一读Netty官方翻译文档。

好了,说了那么多,下面就来HelloWorld入门吧!

服务器端:

[java] view plain copy
  1. public class Server {  
  2.   
  3.     private int port;  
  4.   
  5.     public Server(int port) {  
  6.         this.port = port;  
  7.     }  
  8.   
  9.     public void run() {  
  10.         EventLoopGroup bossGroup = new NioEventLoopGroup(); //用于处理服务器端接收客户端连接  
  11.         EventLoopGroup workerGroup = new NioEventLoopGroup(); //进行网络通信(读写)  
  12.         try {  
  13.             ServerBootstrap bootstrap = new ServerBootstrap(); //辅助工具类,用于服务器通道的一系列配置  
  14.             bootstrap.group(bossGroup, workerGroup) //绑定两个线程组  
  15.                     .channel(NioServerSocketChannel.class//指定NIO的模式  
  16.                     .childHandler(new ChannelInitializer<SocketChannel>() { //配置具体的数据处理方式  
  17.                         @Override  
  18.                         protected void initChannel(SocketChannel socketChannel) throws Exception {  
  19.                             socketChannel.pipeline().addLast(new ServerHandler());  
  20.                         }  
  21.                     })  
  22.                     /** 
  23.                      * 对于ChannelOption.SO_BACKLOG的解释: 
  24.                      * 服务器端TCP内核维护有两个队列,我们称之为A、B队列。客户端向服务器端connect时,会发送带有SYN标志的包(第一次握手),服务器端 
  25.                      * 接收到客户端发送的SYN时,向客户端发送SYN ACK确认(第二次握手),此时TCP内核模块把客户端连接加入到A队列中,然后服务器接收到 
  26.                      * 客户端发送的ACK时(第三次握手),TCP内核模块把客户端连接从A队列移动到B队列,连接完成,应用程序的accept会返回。也就是说accept 
  27.                      * 从B队列中取出完成了三次握手的连接。 
  28.                      * A队列和B队列的长度之和就是backlog。当A、B队列的长度之和大于ChannelOption.SO_BACKLOG时,新的连接将会被TCP内核拒绝。 
  29.                      * 所以,如果backlog过小,可能会出现accept速度跟不上,A、B队列满了,导致新的客户端无法连接。要注意的是,backlog对程序支持的 
  30.                      * 连接数并无影响,backlog影响的只是还没有被accept取出的连接 
  31.                      */  
  32.                     .option(ChannelOption.SO_BACKLOG, 128//设置TCP缓冲区  
  33.                     .option(ChannelOption.SO_SNDBUF, 32 * 1024//设置发送数据缓冲大小  
  34.                     .option(ChannelOption.SO_RCVBUF, 32 * 1024//设置接受数据缓冲大小  
  35.                     .childOption(ChannelOption.SO_KEEPALIVE, true); //保持连接  
  36.             ChannelFuture future = bootstrap.bind(port).sync();  
  37.             future.channel().closeFuture().sync();  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         } finally {  
  41.             workerGroup.shutdownGracefully();  
  42.             bossGroup.shutdownGracefully();  
  43.         }  
  44.     }  
  45.   
  46.     public static void main(String[] args) {  
  47.         new Server(8379).run();  
  48.     }  
  49. }  


ServerHandler类:

客户端:

[java] view plain copy
  1. public class Client {  
  2.   
  3.     public static void main(String[] args) throws InterruptedException {  
  4.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  5.         Bootstrap bootstrap = new Bootstrap();  
  6.         bootstrap.group(workerGroup)  
  7.                 .channel(NioSocketChannel.class)  
  8.                 .handler(new ChannelInitializer<SocketChannel>() {  
  9.                     @Override  
  10.                     protected void initChannel(SocketChannel socketChannel) throws Exception {  
  11.                         socketChannel.pipeline().addLast(new ClientHandler());  
  12.                     }  
  13.                 });  
  14.         ChannelFuture future = bootstrap.connect("127.0.0.1"8379).sync();  
  15.         future.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));  
  16.         future.channel().closeFuture().sync();  
  17.         workerGroup.shutdownGracefully();  
  18.     }  
  19.   
  20. }  

ClientHandler类:
[java] view plain copy
  1. public class ClientHandler extends ChannelHandlerAdapter {  
  2.   
  3.     @Override  
  4.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  5.         try {  
  6.             ByteBuf buf = (ByteBuf) msg;  
  7.             byte[] data = new byte[buf.readableBytes()];  
  8.             buf.readBytes(data);  
  9.             System.out.println("Client:" + new String(data).trim());  
  10.         } finally {  
  11.             ReferenceCountUtil.release(msg);  
  12.         }  
  13.     }  
  14.   
  15.   
  16.     @Override  
  17.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  18.         cause.printStackTrace();  
  19.         ctx.close();  
  20.     }  
  21.   
  22. }  

运行结果:



5.TCP粘包、拆包问题

熟悉TCP编程的可能都知道,无论是服务器端还是客户端,当我们读取或者发送数据的时候,都需要考虑TCP底层的粘包/拆包机制。

TCP是一个“流”协议,所谓流就是没有界限的遗传数据。大家可以想象一下,如果河水就好比数据,他们是连成一片的,没有分界线,TCP底层并不了解上层业务数据的具体含义,它会根据TCP缓冲区的具体情况进行包的划分,也就是说,在业务上一个完整的包可能会被TCP分成多个包进行发送,也可能把多个小包封装成一个大的数据包发送出去,这就是所谓的粘包/拆包问题。

解决方案:

①消息定长,例如每个报文的大小固定为200个字节,如果不够,空位补空格。

②在包尾部增加特殊字符进行分割,例如加回车等。

③将消息分为消息头和消息体,在消息头中包含表示消息总长度的字段,然后进行业务逻辑的处理。

Netty中解决TCP粘包/拆包的方法:

①分隔符类:DelimiterBasedFrameDecoder(自定义分隔符)

②定长:FixedLengthFrameDecoder

6.Netty编解码技术

通常我们也习惯将编码(Encode)成为序列化,它将数据序列化为字节数组,用于网络传输、数据持久化或者其他用途。反之,解码(Decode)/反序列化(deserialization)

把从网络、磁盘等读取的字节数组还原成原始对象(通常是原始对象的拷贝),以方便后续的业务逻辑操作。进行远程跨进程服务调用时(例如RPC调用),需要使用特定的编解码技术,对需要进行网络传输的对象做编码或者解码,以便完成远程调用。

主流的编解码框架:

①JBoss的Marshalling包

②google的Protobuf

③基于Protobuf的Kyro

④MessagePack框架

上代码,一读就懂,注意红色字体(<span style="color:#ff0000;">标签中的内容)部分。

服务器端:

[java] view plain copy
  1. public class Server {  
  2.   
  3.     public Server(int port) {  
  4.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  5.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  6.         try {  
  7.             ServerBootstrap bootstrap = new ServerBootstrap();  
  8.             bootstrap.group(bossGroup, workerGroup)  
  9.                     .channel(NioServerSocketChannel.class)  
  10.                     .handler(new LoggingHandler(LogLevel.INFO))  
  11.                     .childHandler(new ChannelInitializer<SocketChannel>() {  
  12.                         @Override  
  13.                         protected void initChannel(SocketChannel socketChannel) throws Exception {  
  14.                             <span style="color:#ff0000;">socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());  
  15.                             socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());</span>  
  16.                             socketChannel.pipeline().addLast(new ServerHandler());  
  17.                         }  
  18.                     })  
  19.                     .option(ChannelOption.SO_BACKLOG, 1024)  
  20.                     .option(ChannelOption.SO_RCVBUF, 32 * 1024)  
  21.                     .option(ChannelOption.SO_SNDBUF, 32 * 1024)  
  22.                     .option(ChannelOption.SO_KEEPALIVE, true);  
  23.             ChannelFuture future = bootstrap.bind(port).sync();  
  24.             future.channel().closeFuture().sync();  
  25.         } catch (Exception e) {  
  26.             e.printStackTrace();  
  27.         } finally {  
  28.             bossGroup.shutdownGracefully();  
  29.             workerGroup.shutdownGracefully();  
  30.         }  
  31.     }  
  32.   
  33.     public static void main(String[] args) {  
  34.         new Server(8765);  
  35.     }  
  36. }  
ServerHandler类:
[java] view plain copy
  1. public class ServerHandler extends ChannelHandlerAdapter {  
  2.   
  3.     @Override  
  4.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  5.         cause.printStackTrace();  
  6.         ctx.close();  
  7.     }  
  8.   
  9.     @Override  
  10.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  11.         super.channelActive(ctx);  
  12.     }  
  13.   
  14.     @Override  
  15.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  16.         <span style="color:#ff0000;">Request request = (Request) msg;</span>  
  17.         System.out.println("Server:" + request.getId() + "," + request.getName() + "," + request.getReqeustMessag());  
  18.   
  19.         Response response = new Response();  
  20.         response.setId(request.getId());  
  21.         response.setName("response " + request.getId());  
  22.         response.setResponseMessage("响应内容:" + request.getReqeustMessag());  
  23.         byte[] unGizpData = GzipUtils.unGzip(request.getAttachment());  
  24.         char separator = File.separatorChar;  
  25.         FileOutputStream outputStream = new FileOutputStream(System.getProperty("user.dir") + separator + "recieve" + separator + "1.png");  
  26.         outputStream.write(unGizpData);  
  27.         outputStream.flush();  
  28.         outputStream.close();  
  29.         <span style="color:#ff0000;">ctx.writeAndFlush(response);</span>  
  30.     }  
  31. }  
客户端:
[java] view plain copy
  1. public class Client {  
  2.   
  3.     public static void main(String[] args) {  
  4.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  5.         try {  
  6.             Bootstrap bootstrap = new Bootstrap();  
  7.             bootstrap.group(workerGroup)  
  8.                     .handler(new LoggingHandler(LogLevel.INFO))  
  9.                     .channel(NioSocketChannel.class)  
  10.                     .handler(new ChannelInitializer<SocketChannel>() {  
  11.                         @Override  
  12.                         protected void initChannel(SocketChannel socketChannel) throws Exception {  
  13.                             <span style="color:#ff0000;">socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());  
  14.                             socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());</span>  
  15.                             socketChannel.pipeline().addLast(new ClientHandler());  
  16.                         }  
  17.                     });  
  18.             ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.01"8765)).sync();  
  19.             <span style="color:#ff0000;">for(int i=1; i<=5; i++) {  
  20.                 Request request = new Request();  
  21.                 request.setId(i);  
  22.                 request.setName("pro" + i);  
  23.                 request.setReqeustMessag("数据信息" + i);  
  24.                 //传输图片  
  25.                 char separator = File.separatorChar;  
  26.                 File file = new File(System.getProperty("user.dir") + separator + "source" + separator + "2.jpg");  
  27.                 FileInputStream inputStream = new FileInputStream(file);  
  28.                 byte[] data = new byte[inputStream.available()];  
  29.                 inputStream.read(data);  
  30.                 inputStream.close();  
  31.                 byte[] gzipData = GzipUtils.gzip(data);  
  32.                 request.setAttachment(gzipData);  
  33.                 future.channel().writeAndFlush(request);  
  34.             }</span>  
  35.   
  36.             future.channel().closeFuture().sync();  
  37.         } catch (Exception e) {  
  38.             e.printStackTrace();  
  39.         } finally {  
  40.             workerGroup.shutdownGracefully();  
  41.         }  
  42.     }  
  43.   
  44. }  
ClientHandler类:
[java] view plain copy
  1. public class ClientHandler extends ChannelHandlerAdapter {  
  2.     @Override  
  3.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  4.         super.exceptionCaught(ctx, cause);  
  5.     }  
  6.   
  7.     @Override  
  8.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  9.         super.channelActive(ctx);  
  10.     }  
  11.   
  12.     @Override  
  13.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  14.         <span style="color:#ff0000;">Response response = (Response) msg;</span>  
  15.         System.out.println("Client:" + response.getId() + "," + response.getName() + "," + response.getResponseMessage());  
  16.     }  
  17. }  
Marshalling工具类:
[java] view plain copy
  1. public final class MarshallingCodeCFactory {  
  2.   
  3.     /** 
  4.      * 创建Jboss Marshalling解码器MarshallingDecoder 
  5.      * @return MarshallingDecoder 
  6.      */  
  7.     public static MarshallingDecoder buildMarshallingDecoder() {  
  8.         //首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。  
  9.         final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");  
  10.         //创建了MarshallingConfiguration对象,配置了版本号为5   
  11.         final MarshallingConfiguration configuration = new MarshallingConfiguration();  
  12.         configuration.setVersion(5);  
  13.         //根据marshallerFactory和configuration创建provider  
  14.         UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, configuration);  
  15.         //构建Netty的MarshallingDecoder对象,俩个参数分别为provider和单个消息序列化后的最大长度  
  16.         MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024 * 1024);  
  17.         return decoder;  
  18.     }  
  19.   
  20.     /** 
  21.      * 创建Jboss Marshalling编码器MarshallingEncoder 
  22.      * @return MarshallingEncoder 
  23.      */  
  24.     public static MarshallingEncoder buildMarshallingEncoder() {  
  25.         final MarshallerFactory marshallerFactory = Marshalling.getProvidedMarshallerFactory("serial");  
  26.         final MarshallingConfiguration configuration = new MarshallingConfiguration();  
  27.         configuration.setVersion(5);  
  28.         MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, configuration);  
  29.         //构建Netty的MarshallingEncoder对象,MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组  
  30.         MarshallingEncoder encoder = new MarshallingEncoder(provider);  
  31.         return encoder;  
  32.     }  
  33. }  
Gizp压缩与解压缩工具类:
[java] view plain copy
  1. public class GzipUtils {  
  2.     public static byte[] gzip(byte[] val) throws IOException {  
  3.         ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);  
  4.         GZIPOutputStream gos = null;  
  5.         try {  
  6.             gos = new GZIPOutputStream(bos);  
  7.             gos.write(val, 0, val.length);  
  8.             gos.finish();  
  9.             gos.flush();  
  10.             bos.flush();  
  11.             val = bos.toByteArray();  
  12.         } finally {  
  13.             if (gos != null)  
  14.                 gos.close();  
  15.             if (bos != null)  
  16.                 bos.close();  
  17.         }  
  18.         return val;  
  19.     }  
  20.   
  21.     public static byte[] unGzip(byte[] buf) throws IOException {  
  22.         GZIPInputStream gzi = null;  
  23.         ByteArrayOutputStream bos = null;  
  24.         try {  
  25.             gzi = new GZIPInputStream(new ByteArrayInputStream(buf));  
  26.             bos = new ByteArrayOutputStream(buf.length);  
  27.             int count = 0;  
  28.             byte[] tmp = new byte[2048];  
  29.             while ((count = gzi.read(tmp)) != -1) {  
  30.                 bos.write(tmp, 0, count);  
  31.             }  
  32.             buf = bos.toByteArray();  
  33.         } finally {  
  34.             if (bos != null) {  
  35.                 bos.flush();  
  36.                 bos.close();  
  37.             }  
  38.             if (gzi != null)  
  39.                 gzi.close();  
  40.         }  
  41.         return buf;  
  42.     }  
  43. }  

7.最佳实践

(1)数据通信

我们需要了解在真正项目中如何使用Netty,大体上对于一些参数设置都是根据服务器性能决定的。我们需要考虑的问题是两台机器(甚至多台)使用Netty怎样进行通信。

大体上分为三种:
     ①使用长连接通道不断开的形式进行通信,也就是服务器和客户端的通道一直处于开启状态,如果服务器性能足够好,并且客户端数量也比较上的情况下,推荐这种方式。
     ②一次性批量提交数据,采用短连接方式。也就是说先把数据保存到本地临时缓存区或者临时表,当达到界值时进行一次性批量提交,又或者根据定时任务轮询提交,

这种情况的弊端是做不到实时性传输,对实时性要求不高的应用程序中推荐使用。
     ③使用一种特殊的长连接,在某一指定时间段内,服务器与某台客户端没有任何通信,则断开连接。下次连接则是客户端向服务器发送请求的时候,再次建立连接。
     在这里将介绍使用Netty实现第三种方式的连接,但是我们需要考虑两个因素:
     ①如何在超时(即服务器和客户端没有任何通信)后关闭通道?关闭通道后又如何再次建立连接?
     ②客户端宕机时,我们无需考虑,下次重启客户端之后就可以与服务器建立连接,但服务器宕机时,客户端如何与服务器端通信?

服务器端:增加了红色框部分

客户端(注意红色字体部分。PS:<span style="color:#ff0000;">中的内容):

[java] view plain copy
  1. public class Client {  
  2.   
  3.     private static class SingleHodler {  
  4.         static final Client client = new Client();  
  5.     }  
  6.   
  7.     public static Client getInstance() {  
  8.         return SingleHodler.client;  
  9.     }  
  10.   
  11.     private EventLoopGroup workerGroup;  
  12.     private Bootstrap bootstrap;  
  13.     private ChannelFuture future;  
  14.   
  15.     private Client() {  
  16.         workerGroup = new NioEventLoopGroup();  
  17.         bootstrap = new Bootstrap();  
  18.         bootstrap.group(workerGroup)  
  19.                 .channel(NioSocketChannel.class)  
  20.                 .handler(new ChannelInitializer<SocketChannel>() {  
  21.                     @Override  
  22.                     protected void initChannel(SocketChannel socketChannel) throws Exception {  
  23.                         socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());  
  24.                         socketChannel.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());  
  25.                         <span style="color:#ff0000;">socketChannel.pipeline().addLast(new ReadTimeoutHandler(5)); //5秒后未与服务器通信,则断开连接。</span>  
  26.                         socketChannel.pipeline().addLast(new ClientHandler());  
  27.                     }  
  28.                 });  
  29.     }  
  30.   
  31.     public void connect() {  
  32.         try {  
  33.             future = bootstrap.connect("127.0.0.1"8765).sync();  
  34.         } catch (InterruptedException e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.     }  
  38.   
  39.     public ChannelFuture getFuture() {  
  40.         if(future == null || !future.channel().isActive()) {  
  41.             this.connect();  
  42.         }  
  43.         return future;  
  44.     }  
  45.   
  46.     public static void main(String[] args) throws InterruptedException {  
  47.         Client client = getInstance();  
  48.         ChannelFuture future = client.getFuture();  
  49.   
  50.         <span style="color:#ff0000;">for(int i=1; i<=3; i++) {  
  51.             Message message = new Message(i, "pro" + i, "数据信息" + i);  
  52.             future.channel().writeAndFlush(message);  
  53.             Thread.sleep(4000);  //休眠4秒后再发送数据  
  54.         }</span>  
  55.   
  56.         future.channel().closeFuture().sync();  
  57.   
  58.         <span style="color:#ff0000;">new Thread(() -> {  
  59.             try {  
  60.                 System.out.println("子线程开始....");  
  61.                 ChannelFuture f = client.getFuture();  
  62.                 Message message = new Message(4"pro" + 4"数据信息" + 4);  
  63.                 f.channel().writeAndFlush(message);  
  64.                 f.channel().closeFuture().sync();  
  65.             } catch (Exception e) {  
  66.                 e.printStackTrace();  
  67.             }  
  68.         }).start();</span>  
  69.   
  70.         System.out.println("主线程退出......");  
  71.     }  
  72. }  
其他的类与之前的一样,没有变化。

运行结果:



(2)心跳检测

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

这个例子需要使用Sigar,不熟悉的可以看这篇文章。

Server

[java] view plain copy
  1. public class Server {  
  2.     public Server(int port) {  
  3.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  4.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  5.         try {  
  6.             ServerBootstrap bootstrap = new ServerBootstrap();  
  7.             bootstrap.group(bossGroup, workerGroup)  
  8.                     .channel(NioServerSocketChannel.class)  
  9.                     .childHandler(new ChannelInitializer<SocketChannel>() {  
  10.                         @Override  
  11.                         protected void initChannel(SocketChannel sc) throws Exception {  
  12.                             sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());  
  13.                             sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());  
  14.                             sc.pipeline().addLast(new ServerHeartBeatHandler());  
  15.                         }  
  16.                     })  
  17.                     .handler(new LoggingHandler(LogLevel.INFO))  
  18.                     .option(ChannelOption.SO_BACKLOG, 1024);  
  19.             ChannelFuture future = bootstrap.bind(new InetSocketAddress("127.0.0.1", port)).sync();  
  20.             future.channel().closeFuture().sync();  
  21.         } catch (Exception e) {  
  22.             e.printStackTrace();  
  23.         } finally {  
  24.             bossGroup.shutdownGracefully();  
  25.             workerGroup.shutdownGracefully();  
  26.         }  
  27.     }  
  28.   
  29.     public static void main(String[] args) {  
  30.         new Server(8765);  
  31.     }  
  32. }  

ServerHeartBeatHandler类:

[java] view plain copy
  1. public class ServerHeartBeatHandler extends ChannelHandlerAdapter {  
  2.   
  3.     private static Map<String, String> AUTH_IP_MAP = new HashMap<>();  
  4.     private static final String SUCCESS_KEY = "auth_success_key";  
  5.   
  6.     static {  
  7.         AUTH_IP_MAP.put("192.168.3.176""1234");  
  8.     }  
  9.   
  10.     private boolean auth(ChannelHandlerContext ctx, Object msg) {  
  11.         String[] rets = ((String) msg).split(",");  
  12.         String auth = AUTH_IP_MAP.get(rets[0]);  
  13.         if(auth != null && auth.equals(rets[1])) {  
  14.             ctx.writeAndFlush(SUCCESS_KEY);  
  15.             return true;  
  16.         } else {  
  17.             ctx.writeAndFlush("auth failure!").addListener(ChannelFutureListener.CLOSE);  
  18.             return false;  
  19.         }  
  20.     }  
  21.   
  22.     @Override  
  23.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  24.         if(msg instanceof String) {  
  25.             auth(ctx, msg);  
  26.         } else if(msg instanceof RequestInfo) {  
  27.             RequestInfo info = (RequestInfo) msg;  
  28.             System.out.println("----------------------------------------------");  
  29.             System.out.println("当前主机ip:" + info.getIp());  
  30.             System.out.println("当前主机cpu:情况");  
  31.             Map<String, Object> cpuMap = info.getCpuPercMap();  
  32.             System.out.println("总使用率:" +  cpuMap.get("combined"));  
  33.             System.out.println("用户使用率:" + cpuMap.get("user"));  
  34.             System.out.println("系统使用率:" + cpuMap.get("sys"));  
  35.             System.out.println("等待率:" + cpuMap.get("wait"));  
  36.             System.out.println("空闲率:" + cpuMap.get("idle"));  
  37.             System.out.println("当前主机memory情况:");  
  38.             Map<String, Object> memMap = info.getMemoryMap();  
  39.             System.out.println("内存总量:" + memMap.get("total"));  
  40.             System.out.println("当前内存使用量:" + memMap.get("used"));  
  41.             System.out.println("当前内存剩余量:" + memMap.get("free"));  
  42.             System.out.println("-----------------------------------------------");  
  43.             ctx.writeAndFlush("info received!");  
  44.         } else {  
  45.             ctx.writeAndFlush("connect failure").addListener(ChannelFutureListener.CLOSE);  
  46.         }  
  47.     }  
  48. }  
Client类:
[java] view plain copy
  1. public class Client {  
  2.     public static void main(String[] args) {  
  3.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  4.         try {  
  5.             Bootstrap bootstrap = new Bootstrap();  
  6.             bootstrap.group(workerGroup)  
  7.                     .channel(NioSocketChannel.class)  
  8.                     .handler(new ChannelInitializer<SocketChannel>() {  
  9.                         @Override  
  10.                         protected void initChannel(SocketChannel sc) throws Exception {  
  11.                             sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingDecoder());  
  12.                             sc.pipeline().addLast(MarshallingCodeCFactory.buildMarshallingEncoder());  
  13.                             sc.pipeline().addLast(new ClientHeartBeatHandler());  
  14.                         }  
  15.                     });  
  16.             ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1"8765)).sync();  
  17.             future.channel().closeFuture().sync();  
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.         } finally {  
  21.             workerGroup.shutdownGracefully();  
  22.         }  
  23.     }  
  24. }  
ClientHeartBeatHandler类:
[java] view plain copy
  1. public class ClientHeartBeatHandler extends ChannelHandlerAdapter {  
  2.   
  3.     private ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);  
  4.     private ScheduledFuture<?> heartBeat;  
  5.     private InetAddress address;  
  6.     private static final String SUCCESS_KEY = "auth_success_key";  
  7.   
  8.     @Override  
  9.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  10.         address = InetAddress.getLocalHost();  
  11.         String ip = address.getHostAddress();  
  12.         String key = "1234";  
  13.         String auth = ip + "," + key;  
  14.         ctx.writeAndFlush(auth);  
  15.     }  
  16.   
  17.     @Override  
  18.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  19.         cause.printStackTrace();  
  20.         if(heartBeat != null) {  
  21.             heartBeat.cancel(true);  
  22.             heartBeat = null;  
  23.         }  
  24.         ctx.fireExceptionCaught(cause);  
  25.     }  
  26.   
  27.     @Override  
  28.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  29.         try {  
  30.             if(msg instanceof String) {  
  31.                 String data = (String) msg;  
  32.                 if(SUCCESS_KEY.equals(data)) {  
  33.                     heartBeat = scheduled.scheduleWithFixedDelay(new HeartBeatTask(ctx), 05, TimeUnit.SECONDS);  
  34.                     System.out.println(msg);  
  35.                 } else {  
  36.                     System.out.println(msg);  
  37.                 }  
  38.             }  
  39.         } finally {  
  40.             ReferenceCountUtil.release(msg);  
  41.         }  
  42.     }  
  43.   
  44.     private class HeartBeatTask implements Runnable {  
  45.         private final ChannelHandlerContext ctx;  
  46.   
  47.         public HeartBeatTask(ChannelHandlerContext ctx) {  
  48.             this.ctx = ctx;  
  49.         }  
  50.   
  51.         @Override  
  52.         public void run() {  
  53.             try {  
  54.                 RequestInfo requestInfo = new RequestInfo();  
  55.                 requestInfo.setIp(address.getHostAddress());  
  56.                 Sigar sigar = new Sigar();  
  57.                 CpuPerc cpuPerc = sigar.getCpuPerc();  
  58.                 Map<String, Object> cpuPercMap = new HashMap<>();  
  59.                 cpuPercMap.put("combined", cpuPerc.getCombined());  
  60.                 cpuPercMap.put("user", cpuPerc.getUser());  
  61.                 cpuPercMap.put("sys", cpuPerc.getSys());  
  62.                 cpuPercMap.put("wait", cpuPerc.getWait());  
  63.                 cpuPercMap.put("idle", cpuPerc.getIdle());  
  64.   
  65.                 Mem mem = sigar.getMem();  
  66.                 Map<String, Object> memoryMap = new HashMap<>();  
  67.                 memoryMap.put("total", mem.getTotal() / (1024 * 1024));  
  68.                 memoryMap.put("used", mem.getUsed() / (1024 * 1024));  
  69.                 memoryMap.put("free", mem.getFree() / (1024 * 1024));  
  70.   
  71.                 requestInfo.setCpuPercMap(cpuPercMap);  
  72.                 requestInfo.setMemoryMap(memoryMap);  
  73.   
  74.                 ctx.writeAndFlush(requestInfo);  
  75.             } catch (Exception e) {  
  76.                 e.printStackTrace();  
  77.             }  
  78.         }  
  79.     }  
  80. }  
RequestInfo类:
[java] view plain copy
  1. public class RequestInfo implements Serializable {  
  2.   
  3.     private String ip ;  
  4.     private Map<String, Object> cpuPercMap ;  
  5.     private Map<String, Object> memoryMap;  
  6.     //.. other field  
  7.   
  8.     public String getIp() {  
  9.         return ip;  
  10.     }  
  11.   
  12.     public void setIp(String ip) {  
  13.         this.ip = ip;  
  14.     }  
  15.   
  16.     public Map<String, Object> getCpuPercMap() {  
  17.         return cpuPercMap;  
  18.     }  
  19.   
  20.     public void setCpuPercMap(Map<String, Object> cpuPercMap) {  
  21.         this.cpuPercMap = cpuPercMap;  
  22.     }  
  23.   
  24.     public Map<String, Object> getMemoryMap() {  
  25.         return memoryMap;  
  26.     }  
  27.   
  28.     public void setMemoryMap(Map<String, Object> memoryMap) {  
  29.         this.memoryMap = memoryMap;  
  30.     }  
  31. }  
MarshallingCodeCFactory类就不贴出来了,跟之前的一样。

运行结果:



每5秒发送一次数据到服务器端,这样主服务器就可以知道每台从服务器的状态了。当然,这只是一个简单的小例子,真实环境中肯定需要更严格的校验。

阻塞是指客户端向服务器端发起请求,每次只能有一个连接被占用,其余连接在当前线程没有处理完之前都要等待。反之亦然。

非阻塞也容易理解,一个线程可以负载多个连接,新来的客户端可以不用等待。

netty的future主要是配合FutureListener的使用,来达到异步通知的功能。也就是你买奶茶的时候,如果奶茶制作完成,营业员会通过电话来通知你。代码对直接吧Nettty直接拿了过来,做了少许的改动。
原理大概是你只有一个eventloop,然后有selector一样的东西,会在单线程中不断轮询任务。就是说有多个连接,a,b,c 都归这个selector管。selector死循环一样询问 : a,你有事情吗?有,于是开始处理a 花了1s。b你有事情吗?有,又花了1s处理。于是现在是第二秒。最后问c你有事情吗?有,于是处理花了1秒到了第三秒。


异步:
netty的future主要是配合FutureListener的使用,来达到异步通知的功能。也就是你买奶茶的时候,如果奶茶制作完成,营业员会通过电话来通知你。代码对直接吧Nettty直接拿了过来,做了少许的改动。

0 0
原创粉丝点击