多线程Reactor反应器
上一篇介绍了单线程Reactor反应器模式的代码实例。虽然利用NIO模式减少了创建线程的性能损耗,但是由于是单线程,单个反应器内部是阻塞式的。为了加强服务端性能,我们引入多线程模式。引入两个Selector,两个Reactor。代码如下:
public class MultiReactor {
AtomicInteger post = new AtomicInteger(0);
Selector [] selectors = new Selector[2];
SubReactor[] subReactors = new SubReactor[2];
ServerSocketChannel serverSocketChannel;
public MultiReactor(int port) throws IOException {
selectors[0] = Selector.open();
selectors[1] = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.bind(new InetSocketAddress(port));
SelectionKey sk = serverSocketChannel.register(selectors[0], SelectionKey.OP_ACCEPT);
sk.attach(new AcceptHandler());
subReactors[0] = new SubReactor(selectors[0]);
subReactors[1] = new SubReactor(selectors[1]);
}
public void startServer(){
new Thread(subReactors[0]).start();
new Thread(subReactors[1]).start();
}
...
}
SubReactor的实现可以仿照上一篇的Reactor类,这样就是用两个Selector监听一个ServerSocket,使用两个线程响应链接。这里需要注意当Selector没有被注册监听事件,就启动线程调用Selector.select(),会产生阻塞。需要调用Selector.wakeup()方法唤醒线程。所以在ReadHandler中需要增加Selector.wakeup()的调用。
代码片段如下:
//构造函数
ReadHandler(Selector selector, SocketChannel socketChannel){
this.selector = selector;
this.socketChannel = socketChannel;
try {
//注册可读事件
this.socketChannel.configureBlocking(false);
//唤醒Selector
selector.wakeup();
SelectionKey sk = socketChannel.register(selector, 0);
//绑定读Handler(this)
sk.attach(this);
sk.interestOps(SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
}
以上就是多线程Reactor反应器模式的主要代码实现。
Reactor反应器模式总结
从设计模式角度来看反应器模式与生产者消费者模式,以及观察者模式比较类似。反应器模式的主要优点:1.使用NIO,响应快,避免单个链接的同步IO阻塞。2.方便扩展,可以通过增加反应器线程个数充分利用资源。缺点:1.单个反应器是单线程的。一个长时间的数据读写会影响反应器中其他通道的IO处理。