Netty性能测试

Netty性能测试

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

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


从测试结果看,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服务端代码

主程序入口

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

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

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

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


免责声明:此代码只是为了演示Netty性能测试,仅用于学习和研究,切勿用于商业用途。水平有限,错误在所难免,欢迎指正和指导。 。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值