多线程Reactor反应器(Netty 学习六)

多线程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处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值