首页  

netty性能优化点     所属分类 netty 浏览量 1483
使用netty4

netty优化关注点
减少线程切换
复用channel,可以选择池化channel
zero copy 
减少并发下的竞态情况

尽可能复用EventLoopGroup
EventLoop和channel一对多,一个channel被分配给一个EventLoop,生命周期内都会使用这个EventLoop,而EventLoop背后就是线程。
如果使用ThreadLocal保存上下文,那么许多channel就会共享同一个上下文


使用EventLoop的任务调度
// 直接放入channel所对应的EventLoop的执行队列
channel.eventLoop().execute(new Runnable() {
   @Override
    public void run() {
        channel.writeAndFlush(data)
    }
});

// 会导致线程的切换
channel.writeAndFlush(data);


减少ChannelPipline 链路长度
// BAD (most of the times) 消息会经过 整个ChannelPipline
ctx.channel().writeAndFlush(msg);

// GOOD 从当前handler一直到pipline的尾部,链路更短
ctx.writeAndFlush(msg);


减少ChannelHandler的创建
如果channelhandler是无状态的(不保存任何状态参数),那么使用Sharable注解,并在bootstrap时只创建一个实例 ,否则每次连接都会new出handler对象。


减少 Flush 调用
flush操作是将消息发送出去,会引起系统调用


channel复用
对于同一个IP可以复用该channel而不需要重新建立

零拷贝,IO操作时使用池化的DirectBuffer

bootstrap配置参数,指定一个池化的Allocator
option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
ByteBuf buf = allocator.directBuffer()

PooledByteBufAllocator  池化 复用   
IO操作中,分配直接内存而不是JVM的堆空间 ,避免在发送数据时,从JVM到直接内存的拷贝



配置参数优化

ServerBootstrap  bossGroup 只需要设置为 1  
IO 线程,为了充分利用 CPU,同时考虑减少线上下文切换的开销,通常设置为 CPU 核数的两倍
响应时间要求高的场景,禁用nagle算法 ,不等待,立即发送。
.childOption(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.TCP_NODELAY, true)

不要阻塞IO线程 

volatile使用
先将volatile变量保存到方法栈中

// 不好的使用方法
private volatile Selector selector;
public void method() {
  selector.select();
  ....
  selector.selectNow();
}

// 推荐用法 , 将volatile变量保存到方法栈中
private volatile Selector selector;
public void method() {
  Selector selector = this.selector;
  selector.select();
  ....
  selector.selectNow();
}

上一篇     下一篇
spring-boot-starter原理

top使用技巧

netty4耗时业务处理实例

netty ByteBuf 释放说明

eclipse使用用技巧

netty ByteBuf 实战