欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cindy源码阅读(8)Reactor

程序员文章站 2022-05-04 21:19:49
...
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