Reactor反应器模式示例

单线程版本Reactor模式示例

Reactor反应器
/**
 * 单线程版的反应器模式demo
 */
public class EchoServerReactor implements Runnable {
    Selector selector;
    ServerSocketChannel serverSocketChannel;

    public static void main(String[] args) {
        new Thread(new EchoServerReactor()).start();
    }

    void EchoServerReactor() throws Exception{
        //打开选择器
        selector = Selector.open();
        //ServerSocket连接监听通道
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT));
        serverSocketChannel.configureBlocking(false);
        //注册serverSocket的accept事件
        SelectionKey sk = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //将新连接处理器作为附件,绑定到sk选择键
        sk.attach(new AcceptorHandler());
    }

    @Override
    public void run() {
        //选择器轮询
        try {
            while (!Thread.interrupted()) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    //反应器负责dispatch收到的事件
                    SelectionKey sk = it.next();
                    dispatch(sk);

                }
                selectionKeys.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void dispatch(SelectionKey sk) {
        Runnable handler = (Runnable) (sk.attachment());
        //调用之前绑定到选择键的handler处理器对象
        if (handler != null) {
            handler.run();
        }
    }

    //新连接处理器
    class AcceptorHandler implements Runnable{

        @Override
        public void run() {
            //接受新连接
            try {
                SocketChannel channel = serverSocketChannel.accept();
                if (channel != null) {
                    //需要为新连接创建一个输入输出的handler处理器
                    new EchoHandler(selector, channel);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Handler处理器
/**
 * 单线程版处理器
 */
public class EchoHandler implements Runnable {
    final SocketChannel channel;

    final SelectionKey sk;

    final ByteBuffer buffer = ByteBuffer.allocate(NioDemoConfig.SEND_BUFFER_SIZE);

    static final int RECIEVING = 0, SENDING = 1;

    int state = RECIEVING;

    EchoHandler(Selector selector, SocketChannel c) throws IOException {
        channel = c;
        channel.configureBlocking(false);
        //取得选择键,设置感兴趣的IO事件
        sk = channel.register(selector, RECIEVING);
        //将处理器作为选择键的附件
        sk.attach(this);
        //注册Read就绪事件
        sk.interestOps(SelectionKey.OP_READ);
        selector.wakeup();

    }

    @Override
    public void run() {
        try {
            if (state == RECIEVING) {
                //从通道读
                int length = 0;
                while ((length = channel.read(buffer)) > 0) {
                    System.out.println(new String(buffer.array(), 0, length));
                }

                //读完后,准备开始写入通道,buffer切换为读模式
                buffer.flip();
                //读完后,注册write就绪事件
                sk.interestOps(SelectionKey.OP_WRITE);
                //读完后,进入发送状态
                state = SENDING;

            } else if (state == SENDING) {
                //写入通道
                channel.write(buffer);
                //写完后,准备开始从通道读,buffer切换为写模式
                buffer.clear();
                //写完后,注册read就绪事件
                sk.interestOps(SelectionKey.OP_READ);
                //写完后,进入接收状态
                state = RECIEVING;
            }

            //处理结束,不能关闭select_key,需要重复使用
//            sk.cancel();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多线程版本Reactor模式示例

反应器
/**
 * Reactor反应器多线程版本
 */
public class MultiThreadEchoServerReactor {
    ServerSocketChannel serverSocketChannel;

    AtomicInteger next = new AtomicInteger(0);
    //选择器集合,引入多个选择器
    Selector[] selectors = new Selector[2];
    //引入多个子反应器
    SubReactor[] subReactors = null;

    MultiThreadEchoServerReactor() throws IOException {
        //初始化多个选择器
        selectors[0] = Selector.open();
        selectors[1] = Selector.open();
        serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(NioDemoConfig.SOCKET_SERVER_IP, NioDemoConfig.SOCKET_SERVER_PORT);
        serverSocketChannel.socket().bind(address);
        //设置非阻塞
        serverSocketChannel.configureBlocking(false);
        //第一个选择器,负责监控新连接事件
        SelectionKey sk = serverSocketChannel.register(selectors[0], SelectionKey.OP_ACCEPT);
        //绑定Handler: attach新连接监控handler处理器到SelectionKey
        sk.attach(new AcceptorHandler());
        //第一个子反应器,一子反应器负责一个选择器
        SubReactor subReactor1 = new SubReactor(selectors[0]);
        //第二个子反应器,一子反应器负责一个选择器
        SubReactor subReactor2 = new SubReactor(selectors[1]);

        subReactors = new SubReactor[]{subReactor1, subReactor2};

    }

    private void startService() {
        //一个子反应器对应一个线程
        new Thread(subReactors[0]).start();
        new Thread(subReactors[1]).start();
    }

    //子反应器
    class SubReactor implements Runnable {
        //每个线程负责一个选择器的查询和选择
        final Selector selector;

        SubReactor(Selector selector) {
            this.selector = selector;
        }

        @Override
        public void run() {
            while (!Thread.interrupted()) {
                try {
                    while (!Thread.interrupted()) {
                        selector.select();
                        Set<SelectionKey> selectionKeys = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = selectionKeys.iterator();
                        while (iterator.hasNext()) {
                            //反应器负责dispatch收到的事件
                            SelectionKey sk = iterator.next();
                            dispatch(sk);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        private void dispatch(SelectionKey sk) {
            Runnable handler = (Runnable) sk.attachment();
            //调用之前attach绑定到选择键的handler处理器对象
            if (handler != null) {
                handler.run();
            }

        }
    }

    class AcceptorHandler implements Runnable {

        @Override
        public void run() {
            try {
                SocketChannel channel = serverSocketChannel.accept();
                if (channel != null) {
                    new MultiThreadEchoHandler(selectors[next.get()], channel);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (next.incrementAndGet() == selectors.length) {
                next.set(0);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        MultiThreadEchoServerReactor server = new MultiThreadEchoServerReactor();
        server.startService();
    }


}
处理器
public class MultiThreadEchoHandler implements Runnable {
     SocketChannel channel = null;
     SelectionKey sk = null;
    final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    static final int RECEIVE = 0, SENDING = 1;
    int state = RECEIVE;

    //引入线程池
    static ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("MutiThreadEchoHandler-%d").build();
    static ExecutorService pool = new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10), factory, new ThreadPoolExecutor.DiscardPolicy());

    public MultiThreadEchoHandler(Selector selector, SocketChannel channel) {
        try {
            this.channel = channel;
            channel.configureBlocking(false);
            //取得选择键,再设置关注的IO事件
            this.sk = channel.register(selector, RECEIVE);
            //将本handler作为sk选择键的附件,方便事件分发(dispatch)
            sk.attach(this);
            //向选择键注册Read注册事件
            sk.interestOps(SelectionKey.OP_READ);
            selector.wakeup();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        //异步任务,在独立的线程池中执行
        pool.execute(new AsycnRun());
    }

    //异步任务的内部类
    private class AsycnRun implements Runnable {
        @Override
        public void run() {
            MultiThreadEchoHandler.this.asyncRun();
        }
    }

    public synchronized void asyncRun() {

        try {
            if (state == SENDING) {
                //写入通道
                channel.write(byteBuffer);
                byteBuffer.flip();
                sk.interestOps(SelectionKey.OP_READ);
                state = RECEIVE;
            } else if (state == RECEIVE) {
                //从通道读
                int length = 0;
                while ((length = channel.read(byteBuffer)) > 0) {
                    System.out.println(new String(byteBuffer.array(), 0, length));
                }
                byteBuffer.clear();
                sk.interestOps(SelectionKey.OP_WRITE);
                state = RECEIVE;
            }
            //处理结束,还不能关闭select key, 需要重复使用
//            sk.cancel();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值