学习 Doug Lea 大神写的——Scalable IO in Java
学习 Doug Lea 大神写的——Scalable IO in Java
网络服务
Web services、分布式对象等等都具有相同的处理结构
- Read request
- Decode request
- Process service
- Encode reply
- Send reply
基础的网络设计

每一个处理的 handler 都在各自的线程中处理。
代码示例
public class Server01 implements Runnable {
@Override public void run() {
try {
ServerSocket serverSocket = new ServerSocket(9898);
while (!Thread.interrupted()) {
// serverSocket.accept() 会阻塞到有客户端连接,之后 Handler 会处理
new Thread(new Handler(serverSocket.accept())).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) {
this.socket = socket;
}
@Override public void run() {
try {
byte[] input = new byte[1024];
// 假设能全部读取出来
socket.getInputStream().read(input);
byte[] output = process(input);
socket.getOutputStream().write(output);
} catch (Exception e) {
e.printStackTrace();
}
}
private byte[] process(byte[] input) {
// 里面处理逻辑
return new byte[0];
}
}
}
这样做的好处是通过 accept 事件来触发任务的执行,将每个任务单独的去执行。但是缺点也很明显如果客户端链接过大那么需要新建若干个线程去执行,每台服务器可以运行的线程数是有限的。那么多线程的上下文切换的消耗也是巨大的。
Reactor Pattern
首先我们先来看下什么是事件驱动,在 java AWT 包中广泛的得到了使用。用户在点击一个 button 按钮的时候就会触发一个事件,然后会使用观察者模式来触发 Listener 中的处理事件。

Reactor 设计模式是基于事件驱动的一种实现方式,处理多个客户端并发的向服务端请求服务的场景。每种服务在服务端可能由多个方法组成。reactor 会解耦并发请求的服务并分发给对应的事件处理器来处理。目前,许多流行的开源框架都用到了。类似 AWT 中的 Thread。
Handlers 执行非阻塞操作的具体类,类似 AWT 中的 ActionListeners。
Reactor 单线程处理任务的设计

代码示例
public class Reactor implements Runnable {
private final Selector selector;
private final ServerSocketChannel serverSocketChannel;
public Reactor(int port) throws IOException {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
selectionKey.attach(new Acceptor());
}
@Override public void run() {
try {
while (!Thread.interrupted()) {
selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
for (SelectionKey selectionKey : selectionKeys) {
dispatch(selectionKey);
selectionKeys.clear();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void dispatch(SelectionKey selectionKey) {
Runnable runnable = (Runnable) selectionKey.attachment();
if (null != runnable) {
runnable.run();
}
}
private class Acceptor implements Runnable {
@Override public void run() {
try {
SocketChannel socketChannel = serverSocketChannel.accept();
if (null != socketChannel) {
new Handler(selector, socketChannel);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Handler implements Runnable {
private final SocketChannel socketChannel;
private final SelectionKey selectionKey;
private ByteBuffer input = ByteBuffer.allocate(1024);
private ByteBuffer output = ByteBuffer.allocate(1024);
private static final int READING = 0, SENDING = 1;
private int state = READING;
Handler(Selector selector, SocketChannel socketChannel) throws IOException {
this.socketChannel = socketChannel;
this.socketChannel.configureBlocking(false);
selectionKey = this.socketChannel.register(selector, 0);
selectionKey.attach(this);
selectionKey.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}
void process() {
}
@Override public void run() {
try {
if (state == READING) {
socketChannel.read(input);
process();
state = SENDING;
selectionKey.interestOps(SelectionKey.OP_WRITE);
}
if (state == READING) {
socketChannel.write(output);
selectionKey.cancel();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这个程序的重点在于 selectionKey.attach(); 方法每次把需要的对象传入进去,之后在有事件触发的时候会在 dispatch 中 attachment() 获取到这个对象,之后直接调用 run 方法。
Reactor 多线程处理任务的设计

只需要稍微修改下 Handler 这个类
// 添加一个线程池开发时请使用自定义或 spring 的线程池
private final ExecutorService executorService = Executors.newCachedThreadPool();
// 修改 run 方法
@Override public void run() {
try {
if (state == READING) {
socketChannel.read(input);
executorService.execute(new Runnable() {
@Override public void run() {
process();
state = SENDING;
selectionKey.interestOps(SelectionKey.OP_WRITE);
}
});
}
if (state == READING) {
socketChannel.write(output);
selectionKey.cancel();
}
} catch (Exception e) {
e.printStackTrace();
}
}
多个 Reactor

当看到这幅图的时候感觉这不就是 Netty EventLoopGroup 的工作模式吗
- mainReactor 不就是 bossGroup
- subReactor 不就是 workGroup
至此粗略的看完了这篇文章,感觉太 6 了,需要后面重复学习,这次只是了解大概。后面学习完会持续更新这篇文章!
学习 Doug Lea 大神写的——Scalable IO in Java的更多相关文章
- Netty Reator(二)Scalable IO in Java
Netty Reator(二)Scalable IO in Java Netty 系列目录 (https://www.cnblogs.com/binarylei/p/10117436.html) Do ...
- 【精尽Netty源码解析】1.Scalable IO in Java——多Reactor的代码实现
Java高伸缩性IO处理 在Doug Lea大神的经典NIO框架文章<Scalable IO in Java>中,具体阐述了如何把Reactor模式和Java NIO整合起来,一步步理论结 ...
- 《Scalable IO in Java》译文
<Scalable IO in Java> 是java.util.concurrent包的作者,大师Doug Lea关于分析与构建可伸缩的高性能IO服务的一篇经典文章,在文章中Doug L ...
- 一文弄懂-《Scalable IO In Java》
目录 一. <Scalable IO In Java> 是什么? 二. IO架构的演变历程 1. Classic Service Designs 经典服务模型 2. Event-drive ...
- 《Scalable IO in Java》笔记
Scalable IO in Java http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf 基本上所有的网络处理程序都有以下基本的处理过程:Read reque ...
- Scalable IO in Java
Scalable IO in Java http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf 大部分IO都是下面这个步骤, Most have same basi ...
- 五月的仓颉大神写的 三年java程序员面试感悟 值得分享给大家
感谢 五月的仓颉 的这篇文章 , 让我重新认识到自己身上的不足之处 . 原文地址http://www.cnblogs.com/xrq730/p/5260294.html,转载请注明出处,谢谢! 前 ...
- 学习Python不得不关注和学习的国外大神博客
注意 : 本文收集于网路 . 由于常常更新 , 有些链接打不开, 请自备梯子 在学习Python过程中,总会遇到各种各样的坑, 虽然Python是一门优美而简单易学的语言 . 但当学习后 , 总想着更 ...
- 大神为你分析 Go、Java、C 等主流编程语言(Go可以替代Java,而且最小化程序员的工作量,学习比较容易)
本文主要分析 C.C++98.C++11.Java 与 Go,主要论述语言的关键能力.在论述的过程中会结合华为各语言编程专家和华为电信软件内部的骨干开发人员的交流,摒弃语言偏好或者语言教派之争,尽量以 ...
随机推荐
- 软件-平面设计-CorelDRAW:CorelDRAW
ylbtech-软件-平面设计-CorelDRAW:CorelDRAW CorelDRAW Graphics Suite是加拿大Corel公司的平面设计软件:该软件是Corel公司出品的矢量图形制作工 ...
- npm ERR! cb() never called! npm ERR! This is an error with npm itself. Pleas
原因是:需要用管理员的身份才能进行 方法:点开始,找到命令提示符,右键,点以管理员的身份运行命令即可
- 64位系统sql链接oracle
在SQL Server 2008中连接Oracle,完成查询.插入操作 建立指向Oracle的连接 在32位的系统中sql链接oracle,在链接服务器里点击服务器对象,右键链接服务器,选择micro ...
- Django框架(三十)—— 使用Vue搭建前台
目录 vue的使用 一.创建vue项目 二.pycharm开发vue项目 1.安装vue.js插件 2.运行vue项目 三.vue项目的目录结构 四.vue的使用 1.创建新的组件 2.显示数据 3. ...
- 关于Oracle中Sort Merge Join的改写
业务场景的问题,我们有一个刷CUBE的SQL,是Oracle环境,平时跑70多分钟, 但是最近突然不动了,这个SQL需要算累计值,比如年累计客户数量. 累计值是什么意思呢?我们使用下面的数据来说明问题 ...
- 一文读懂MQTT协议
1 概述 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的"轻量级 ...
- stdin stdout stderr - 标准 I/O 流
Fd #include <stdio.h> Fd extern FILE *stdin; Fd extern FILE *stdout; Fd extern FILE *stderr; D ...
- 第2篇Kubernetes架构
一.Kubernetes 架构: Kubernetes Cluster 由 Master 和 Node 组成,节点上运行着若干 Kubernetes 服务. Master 节点 Master 是 ...
- volatile(防止编译器对代码进行优化)
adj.易变的:无定性的:无常性的:可能急剧波动的 网络挥发性:挥发性的:不稳定的 volatile的变量是说这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了.
- model字段对象和forms字段对象的区别和联系
一.model字段对象 (一)_meta _meta是django.db.models.options.Options的实例,获取字段对象可通过模型类来进行获取,而_meta可提供如下功能: 获取模型 ...