反应器(Reactor)模式

[b][size=small]概述[/size][/b]
Java NIO非堵塞技术实际是采取反应器模式,或者说是观察者(observer)模式为我们监察I/O端口,如果有内容进来,会自动通知我们,这样,我们就不必开启多个线程死等,从外界看,实现了流畅的I/O读写,不堵塞了。

同步和异步的区别:有无通知(是否轮询)
阻塞与非阻塞的区别:操作结果是否等待(是否马上有返回值),只是设计方式的不同

NIO 有一个主要的类Selector,这个类似一个观察者,只要我们把需要探知的socketchannel告诉Selector,我们接着做别的事情,当有事件发生时,他会通知我们,传回一组SelectionKey,我们读取这些Key,就会获得我们刚刚注册过的socketchannel,然后,我们从这个Channel中读取数据,接着我们可以处理这些数据。

反应器模式与观察者模式在某些方面极为相似:当一个主体发生改变时,所有依属体都得到通知。不过,观察者模式与单个事件源关联,而反应器模式则与多个事件源关联 。

[b][size=small]一般模型[/size][/b]
我们想象以下情形:长途客车在路途上,有人上车有人下车,但是乘客总是希望能够在客车上得到休息。

传统的做法是:每隔一段时间(或每一个站),司机或售票员对每一个乘客询问是否下车。

反应器模式做法是:汽车是乘客访问的主体(Reactor),乘客上车后,到售票员(acceptor)处登记,之后乘客便可以休息睡觉去了,当到达乘客所要到达的目的地后,售票员将其唤醒即可。

原理图:
[img]http://dl2.iteye.com/upload/attachment/0115/2383/0e188d22-e97a-32ef-8422-a43d33896f1e.png[/img]


package com.cbf4life.reactor;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
* @Description:反应器模式,解决多用户并发访问问题
* 举例:餐厅服务
* 传统线程池做法:来一个客人(请求)请求一个服务员(线程)
* 反应器模式做法:当客人点菜的时候,服务员就可以去招呼其他客人了,等客人点好了菜,直接招呼一声“服务员”
* @Author: xiaoyun
* @Company: http://blog.csdn.net
* @CreateDate: 2016-2-20
*/
public class Reactor implements Runnable {

// 初始化选择器
public final Selector selector;
// 初始化通道
public final ServerSocketChannel serverSocketChannel;

public Reactor(int port) throws IOException {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(), port);
serverSocketChannel.socket().bind(inetSocketAddress);
serverSocketChannel.configureBlocking(false);

// 向选择器中注册该通道
SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
// 利用selectionKey的attach方法绑定Acceptor,如果有请求过来,那么出发Acceptor
key.attach(new Acceptor(this));
}

@Override
public void run() {
try {
while(!Thread.interrupted()) {
selector.select();
Set<SelectionKey> selectionKeys= selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator();
// Selector中如果发现channel中有OP_ACCEPT或者READ事件发生,下列遍历就会运行
while(it.hasNext()) {
// 来一个事件,第一次触发一个accepter线程
// 以后触发SockReadHander
SelectionKey key = it.next();
dispatch(key);
}
selectionKeys.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}

public void dispatch(SelectionKey key) {
Runnable r = (Runnable)key.attachment();
if(r != null) {
r.run();
}
}

}


package com.cbf4life.reactor;

import java.io.IOException;
import java.nio.channels.SocketChannel;

/**
* @Description: 任务处理器
* @Author: xiaoyun
* @Company: http://blog.csdn.net
* @CreateDate: 2016-2-20
*/
public class Acceptor implements Runnable {

private Reactor reactor;

public Acceptor(Reactor reactor) {
this.reactor = reactor;
}

@Override
public void run() {
try {
SocketChannel socketChannel = reactor.serverSocketChannel.accept();
if(socketChannel != null) {
SocketReadHandler handler = new SocketReadHandler(reactor.selector, socketChannel);
}
} catch (IOException e) {
e.printStackTrace();
}

}

}

package com.cbf4life.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* @Description:执行器
* @Author: xiaoyun
* @Company: http://java.itcast.cn
* @CreateDate: 2016-2-20
*/
public class SocketReadHandler implements Runnable {

private SocketChannel socketChannel;

public SocketReadHandler(Selector selector, SocketChannel socketChannel) throws IOException {
this.socketChannel = socketChannel;
socketChannel.configureBlocking(false);
SelectionKey key = socketChannel.register(selector, 0);

// 将选择器的key值绑定为本handler,下一步有事件触发时,将调用本类的run方法
key.attach(this);
// 将该selectionKey标记为可读,以便读取
key.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}

/**
* 处理读取的数据
*/
@Override
public void run() {
ByteBuffer inputBuffer = ByteBuffer.allocate(1024);
// 设置开始位置为0,结束为止为缓存字节长度
inputBuffer.clear();
try {
socketChannel.read(inputBuffer);
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(this);
} catch (IOException e) {
e.printStackTrace();
}
}

}




该文章转载自:[url]http://blog.csdn.net/linxcool/article/details/7771952[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值