参考:html
http://m.oschina.net/blog/527583?from=timeline&isappinstalled=1java
https://lwn.net/Articles/542629/bootstrap
http://www.tuicool.com/articles/Rry6biFapp
http://www.blogjava.net/yongboy/archive/2015/02/25/423037.html !!!框架
默认状况下,用Netty-4.0.33 ,启动的线程只有1个。函数
可是现网的流量确实比较大怎么办?oop
就须要去改造源码。性能
==========测试
通过分析,注册udp channel的线程栈以下所示:ui
通过源码排查,
at io.netty.channel.SingleThreadEventLoop.register(SingleThreadEventLoop.java:48)
at io.netty.channel.MultithreadEventLoopGroup.register(MultithreadEventLoopGroup.java:64)
问题在这里,若是去看源码就知道
找到缘由,就好办了,前进的方向也就有了!
=================================
修改方案:
1 添加一个参数
io.netty.channel.ChannelOption添加以下:
public static final ChannelOption<Boolean> SO_REUSEPORT = valueOf("SO_REUSEPORT");
2使用起来这个参数
启动框架里添加这么一行
.option(ChannelOption.SO_REUSEPORT, true)
同时也添加
.option(ChannelOption.SO_REUSEADDR, true)
3 触发屡次绑定操做
主函数修改后的代码以下:
public void start() {
int totalThreads = SystemPropertyUtil.getInt("io.netty.eventLoopThreads",
Runtime.getRuntime().availableProcessors() * 2);
EventLoopGroup group = new NioEventLoopGroup(totalThreads);
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioDatagramChannel.class)
.option(ChannelOption.SO_BROADCAST, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_REUSEPORT, true)
.handler(new UDPServerHandler());
ChannelFuture futures[] = new ChannelFuture[totalThreads];
for (int i = 0; i < totalThreads; i++) {// 为了启动相应的线程
futures[i] = b.bind(port).sync();
}
for (int i = 0; i < totalThreads; i++) {// 为了等待相应的线程关闭
futures[i].channel().closeFuture().await();
}
} catch (InterruptedException e) {
logger.error("", e);
} finally {
group.shutdownGracefully();
}
}
4 异常处理
此时报异常:
这个异常却是很奇怪。
这个问题怎么解决呢。。。
把主函数的代码修改下
.handler(new UDPServerHandler());这个是必需要保留的,不然会报错。
而后在类io.netty.bootstrap.Bootstrap.init(Bootstrap.java:182)
这里的代码从p.addLast(handler());修改为
p.addLast(new UDPServerHandler());
再来测试看看:成功启动了。
至少线程启动了。
客户端发点数据看看结果:
发现始终是同一个线程处理,这个问题就比较麻烦,咱们的客户机是同一个主机。
这个问题怎么解决呢?
看到一个文章: http://blog.csdn.net/dog250/article/details/17061277
至少能够在发送端设置不一样的端口解决这个问题,性能能够提高,有兴趣的本身试验下。