Future-Listener机制
其逻辑和AJAX一样,通过监听事件来回调方法
代码逻辑:
serverBootstrap.bind(port).addListener(future->{if(future.isSuccess()){system.out.println(newDate()+":port:"+port+"绑定成功");}else{System.err.println(newDate()+"port"+port+"绑定失败")}})
相比同步IO,异步IO可以避免线程阻塞,高并发情况下会有更稳定和更高的吞吐量
如下是 nettyserver 完整的代码示例
public class NettyServer {public static void main(String[] args) {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();
// 创建服务器端的启动对象,配置参数ServerBootstrap bootstrap = new ServerBootstrap();
// 使用链式编程来进行设置bootstrap.group(bossGroup,workerGroup) //设置两个线程池组.channel(NioServerSocketChannel.class) //NioServerSocketChannel 作为服务器的通道实现.option(ChannelOption.SO_BACKLOG,128) //设置线程队列得到连接个数.childOption(ChannelOption.SO_KEEPALIVE,true) //设置保活连接状态.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new NettyServerHandler());}}) ;//给workerGroup的EventLoop对应的管道设置处理器System.out.println("...服务器 isready ...");
// 绑定一个端口并且同步,生成一个channelfuture 对象
// 启动服务器(绑定端口)try {ChannelFuture cf = bootstrap.bind(6668).sync();
// 异步开始监听cf.addListener(new ChannelFutureListener() {@Override
/*** isDone() 判断当前操作是否完成* isSuccess() 判断已经完成的当前操作是否成功* getCause() 判断已经完成的当前操作失败原因* isCancelled() 判断已经完成的当前操作是否被取消* addListener() 注册监听器,当操作已经完成(isDone 返回成功),将会通知指定监听器,如果Future已经完成,则通知指定的监听器* */ public void operationComplete(ChannelFuture channelFuture) throws Exception {if(cf.isSuccess()){System.out.println("监听端口 6668 成功");}else {System.out.println("监听端口 6668 失败");}}});
// 对关闭通道进行监听
// cf.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();}}
}