cindy源码阅读(8)Reactor

阅读更多
public interface Reactor {

    void register(ReactorHandler handler);

    void deregister(ReactorHandler handler);

    void interest(ReactorHandler handler, int ops);


看起来Reactor 是蛮简单的,但是却是困惑我最久的地方。

  public void run() {
                    try {
                        while (!close) {
                            beforeSelect();
                            if (close) // after beforeSelect, close may be true
                                break;
                            try {
                                selector.select(SELECT_TIMEOUT);
                            } catch (IOException e) {
                                log.error(e, e);
                                break;
                            }
                            afterSelect();
                        }
                    } finally {
                        DefaultReactor.this.stop();
                    }
                }

Reactor启动之后,会不停的通过selector去查看各个频道的状态,然后通过ReactorHandler 执行对应状态的操作。

private void processSelectedKeys() {
        for (Iterator iter = selector.selectedKeys().iterator(); iter.hasNext();) {
            SelectionKey key = (SelectionKey) iter.next();
            iter.remove();

            key.interestOps(key.interestOps() & ~key.readyOps());
            Attachment attachment = (Attachment) key.attachment();
            ReactorHandler handler = attachment.handler;

            if (key.isWritable()) // do not check session timeout when writing
                attachment.writing = true;

            if (key.isAcceptable())
                handler.onAcceptable();
            if (key.isConnectable())
                handler.onConnectable();
            if (key.isValid() && key.isReadable())
                handler.onReadable();
            if (key.isValid() && key.isWritable())
                handler.onWritable();
        }
    }


那session的sockerchannel怎么和selector产生联系呢。通过register和deregister方法。那状态的改变呢,是通过interest方法。

ReactorHandler是怎么执行的呢。基本上是通过SessionFilterChain执行对应的方法。SessionFilter可以直接通过session添加:session.addSessionFilter(XXX);

你可能感兴趣的:(cindy,Reactor)