一篇netty性能测试及测试代码

转自:https://blog.csdn.net/doutao6677/article/details/54022333

 

Netty性能测试

Netty是由JBOSS提供的一个Java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。Netty 是一个基于NIO的客户,服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。

Netty简化socket编程,并没有使写出来的Socket效率变低,我写了一个所有都使用默认配置的服务端,模拟最常用的RPC方案,传输协议使用4字节长度加json串的方式来传输,测试服务端的通讯效率,测试结果如下。

一篇netty性能测试及测试代码

从测试结果看,Netty性能是非常高的,在所有使用默认配置的情况下,单台服务器能够达到4万次请求解析,作为RPC框架是足够用的。还有一个有趣的现象是每次都创建连接和重用连接的差别不大,性能损耗对应用层几乎没影响,但是大家如果在应用环境中使用每次新建的情况,一定要进行压测,确认没影响后再使用。

测试用例说明

  1. 部署1台Netty服务器,部署8台并发测试客户端,每个客户端跑1024个并发;
  2. 分为1次连接请求1000次数据和1次连接请求1次数据循环1000次;
  3. Netty服务器为Cent OS 6.5 64位,阿里云8核16G内存,JVM使用默认配置,没有进行任何调优;
  4. 并发客户端为Windows Server 2008 R2  64位企业版,阿里云8核16G内存,NET Framework 4.5运行环境,没有进行任何调优;
  5. 通讯数据格式为:4字节长度+JSON串,服务器负责接收JSON串,进行解析和返回;

Netty服务端代码

主程序入口

[java] view plain copy

  1. public class AppNettyServer {  
  2.   
  3.     public static void main(String[] args) throws Exception {  
  4.         System.out.print("Hello Netty\r\n");  
  5.   
  6.         int port = 9090;  
  7.         if (args != null && args.length > 0) {  
  8.             try {  
  9.                 port = Integer.valueOf(args[0]);  
  10.             } catch (NumberFormatException e) {  
  11.                 System.out.print("Invalid Port, Start Default Port: 9090");  
  12.             }  
  13.         }  
  14.         try {  
  15.             NettyCommandServer commandServer = new NettyCommandServer();  
  16.             System.out.print("Start listen socket, port " + port + "\r\n");  
  17.             commandServer.bind(port);  
  18.         } catch (Exception e) {  
  19.             System.out.print(e.getMessage());  
  20.         }  
  21.     }  
  22. }  

Netty服务端初始化

[java] view plain copy

  1. public class NettyCommandServer {  
  2.   
  3.     public static InternalLogger logger = InternalLoggerFactory.getInstance(NettyCommandServer.class);  
  4.   
  5.     public void bind(int port) throws Exception {  
  6.         EventLoopGroup bossGroup = new NioEventLoopGroup();  
  7.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  8.         try {  
  9.             ServerBootstrap serverBootstrap = new ServerBootstrap();  
  10.             serverBootstrap.group(bossGroup, workerGroup);  
  11.             serverBootstrap.channel(NioServerSocketChannel.class);  
  12.             serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);  
  13.             serverBootstrap.handler(new LoggingHandler());  
  14.             serverBootstrap.childHandler(new NettyChannelHandler());  
  15.             ChannelFuture channelFuture = serverBootstrap.bind(port).sync();  
  16.             channelFuture.channel().closeFuture().sync();  
  17.         } finally {  
  18.             bossGroup.shutdownGracefully();  
  19.             workerGroup.shutdownGracefully();  
  20.         }  
  21.     }  
  22.   
  23.     private class NettyChannelHandler extends ChannelInitializer<SocketChannel> {  
  24.   
  25.         @Override  
  26.         protected void initChannel(SocketChannel socketChannel)  
  27.                 throws Exception {  
  28.             socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(ByteOrder.BIG_ENDIAN, 64 * 1024, 0, 4, 0, 4, true));  
  29.             socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));  
  30.             socketChannel.pipeline().addLast(new NettyCommandHandler());  
  31.         }  
  32.     }  
  33. }  

通讯协议解析数据

[java] view plain copy

  1. public class NettyCommandHandler extends ChannelHandlerAdapter {  
  2.     private int counter = 0;  
  3.   
  4.     @Override  
  5.     public void channelRead(ChannelHandlerContext ctx, Object msg) {  
  6.         try {  
  7.             String body = (String) msg;  
  8.             JsonDataObject request = JsonUtil.fromJson(body, JsonDataObject.class);  
  9.   
  10.             counter = counter + 1;  
  11.             JsonDataObject response = new JsonDataObject();  
  12.             response.setCode(0);  
  13.             response.setMsg("Success");  
  14.             response.setData(counter+"");  
  15.             String respJson = JsonUtil.toJson(response);  
  16.   
  17.             byte[] respUtf8 = respJson.getBytes("UTF-8");  
  18.             int respLength = respUtf8.length;  
  19.             ByteBuf respLengthBuf = PooledByteBufAllocator.DEFAULT.buffer(4);  
  20.             respLengthBuf.writeInt(respLength);  
  21.             respLengthBuf.order(ByteOrder.BIG_ENDIAN);  
  22.             ctx.write(respLengthBuf);  
  23.             ByteBuf resp = PooledByteBufAllocator.DEFAULT.buffer(respUtf8.length);  
  24.             resp.writeBytes(respUtf8);  
  25.             ctx.write(resp);  
  26.         } catch (Exception e) {  
  27.             NettyCommandServer.logger.error(e.getMessage() + "\r\n");  
  28.             StringWriter sw = new StringWriter();  
  29.             PrintWriter pw = new PrintWriter(sw);  
  30.             e.printStackTrace(pw);  
  31.             pw.flush();  
  32.             sw.flush();  
  33.             NettyCommandServer.logger.error(sw.toString());  
  34.         }  
  35.     }  
  36.   
  37.     @Override  
  38.     public void channelReadComplete(ChannelHandlerContext ctx) {  
  39.         ctx.flush();  
  40.     }  
  41.   
  42.     @Override  
  43.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {  
  44.         ctx.close();  
  45.     }  
  46. }  

C#客户端代码

[csharp] view plain copy

  1. public class SocketClient : Object  
  2. {  
  3.     private TcpClient tcpClient;  
  4.   
  5.     public SocketClient()  
  6.     {  
  7.         tcpClient = new TcpClient();  
  8.         tcpClient.Client.Blocking = true;  
  9.     }  
  10.   
  11.     public void Connect(string host, int port)  
  12.     {  
  13.         tcpClient.Connect(host, port);  
  14.     }  
  15.   
  16.     public void Disconnect()  
  17.     {  
  18.         tcpClient.Close();  
  19.     }  
  20.   
  21.     public string SendJson(string json)  
  22.     {  
  23.         byte[] bufferUTF8 = Encoding.UTF8.GetBytes(json);  
  24.         int jsonLength = System.Net.IPAddress.HostToNetworkOrder(bufferUTF8.Length); //转换为网络字节顺序,大头结构  
  25.         byte[] bufferLength = BitConverter.GetBytes(jsonLength);  
  26.         tcpClient.Client.Send(bufferLength, 0, bufferLength.Length, SocketFlags.None); //发送4字节长度  
  27.         tcpClient.Client.Send(bufferUTF8, 0, bufferUTF8.Length, SocketFlags.None); //发送Json串内容  
  28.   
  29.         byte[] bufferRecvLength = new byte[sizeof(int)];  
  30.         tcpClient.Client.Receive(bufferRecvLength, sizeof(int), SocketFlags.None); //获取长度  
  31.         int recvLength = BitConverter.ToInt32(bufferRecvLength, 0);  
  32.         recvLength = System.Net.IPAddress.NetworkToHostOrder(recvLength); //转为本地字节顺序  
  33.         byte[] bufferRecvUtf8 = new byte[recvLength];  
  34.         tcpClient.Client.Receive(bufferRecvUtf8, recvLength, SocketFlags.None);  
  35.         string recvCommand = Encoding.UTF8.GetString(bufferRecvUtf8, 0, recvLength);  
  36.         return recvCommand;  
  37.     }  
  38. }