学习 Doug Lea 大神写的——Scalable IO in Java


网络服务

Web services、分布式对象等等都具有相同的处理结构

  1. Read request
  2. Decode request
  3. Process service
  4. Encode reply
  5. 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 的工作模式吗

  1. mainReactor 不就是 bossGroup
  2. subReactor 不就是 workGroup

至此粗略的看完了这篇文章,感觉太 6 了,需要后面重复学习,这次只是了解大概。后面学习完会持续更新这篇文章!

学习 Doug Lea 大神写的——Scalable IO in Java的更多相关文章

  1. Netty Reator(二)Scalable IO in Java

    Netty Reator(二)Scalable IO in Java Netty 系列目录 (https://www.cnblogs.com/binarylei/p/10117436.html) Do ...

  2. 【精尽Netty源码解析】1.Scalable IO in Java——多Reactor的代码实现

    Java高伸缩性IO处理 在Doug Lea大神的经典NIO框架文章<Scalable IO in Java>中,具体阐述了如何把Reactor模式和Java NIO整合起来,一步步理论结 ...

  3. 《Scalable IO in Java》译文

    <Scalable IO in Java> 是java.util.concurrent包的作者,大师Doug Lea关于分析与构建可伸缩的高性能IO服务的一篇经典文章,在文章中Doug L ...

  4. 一文弄懂-《Scalable IO In Java》

    目录 一. <Scalable IO In Java> 是什么? 二. IO架构的演变历程 1. Classic Service Designs 经典服务模型 2. Event-drive ...

  5. 《Scalable IO in Java》笔记

    Scalable IO in Java http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf 基本上所有的网络处理程序都有以下基本的处理过程:Read reque ...

  6. Scalable IO in Java

    Scalable IO in Java http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf 大部分IO都是下面这个步骤, Most have same basi ...

  7. 五月的仓颉大神写的 三年java程序员面试感悟 值得分享给大家

    感谢 五月的仓颉  的这篇文章 , 让我重新认识到自己身上的不足之处 .  原文地址http://www.cnblogs.com/xrq730/p/5260294.html,转载请注明出处,谢谢! 前 ...

  8. 学习Python不得不关注和学习的国外大神博客

    注意 : 本文收集于网路 . 由于常常更新 , 有些链接打不开, 请自备梯子 在学习Python过程中,总会遇到各种各样的坑, 虽然Python是一门优美而简单易学的语言 . 但当学习后 , 总想着更 ...

  9. 大神为你分析 Go、Java、C 等主流编程语言(Go可以替代Java,而且最小化程序员的工作量,学习比较容易)

    本文主要分析 C.C++98.C++11.Java 与 Go,主要论述语言的关键能力.在论述的过程中会结合华为各语言编程专家和华为电信软件内部的骨干开发人员的交流,摒弃语言偏好或者语言教派之争,尽量以 ...

随机推荐

  1. SQL之in和like的连用实现范围内的模糊查询

    我们知道in可以实现一个范围内的查询,like可以实现模糊查询, 如 select *where col like 123%但是我们如果有一列attri,如123,132,165... 我们想实现12 ...

  2. 在使用 Eclisp 生成 实体(sql Server) 出现错误 :Unable to locate JAR/zip in file system as specified by the driver definition: sqljdbc.jar.

    错误: 解决方法: 第一步:点击 JAR List 第二步:  点击  Remove  JAR/ZIP 第三步: 再添加一下 sqljdbc.jar

  3. 【C++第一个Demo】---控制台RPG游戏2【通用宏、背包类】

    [通用 ]--一些游戏中常用的宏.函数和枚举 #ifndef _MARCO_H_ #define _MARCO_H_ //------------------------常用系统库---------- ...

  4. python作业/练习/实战:1、简单登录脚本

    作业要求 写一个登陆的小程序 username = xiaoming passwd = 123456 1.输入账号密码,输入正确就登陆成功, 提示:欢迎xxxx登陆,今天的日期是xxx. 2.输入错误 ...

  5. redis性能

  6. vue-resource请求

    man.js引入 import Vue from 'vue' import VueResource from 'vue-resource' import App from './App.vue' Vu ...

  7. 使用navigator.userAgent来判断浏览器类型

    var br=navigator.userAgent.toLowerCase(); var browserVer=(br.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ...

  8. ElasticSearch---初识

    1.概述 1.1 ElasticSearch是一个   基于Lucene   的  搜索服务器: 1.2 ElasticSearch 提供了一个分布式多用户能力的全文搜索引擎,基于  RESTful ...

  9. js过滤字符串中的html标签

    var str = 'add<a>daad</a><p>fsdada</p>' str.replace(/<[^<>]+>/g, ...

  10. idea关联git后 Git上传项目提示Push rejected: Push to origin/master was rejected解决办法

    当所有的东西都配好以后  就是不上数据  解决方案是在所属右键 点击Git BashHere后  输入:git pull origin master –allow-unrelated-historie ...