zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Netty源码之Reactor模式

2023-03-07 09:50:23 时间

 

学习目标

  • 什么是Reactor模式?
  • Reactor模式由什么组成的?
  • Reactor模式解决什么问题?
  • Reactor模式线程模型有哪些?演进过程?

web处理请求架构

大多数web请求处理流程可以抽象成这几个步骤:读取(read),解码(decode),处理(process),编码(encode),发送(send),如下图所示:

 

同时,处理web请求通常有两种架构:传统基于线程架构和事件驱动架构。

传统基于线程架构

概念

每个新连接创建一个线程来处理。对于长连接服务,如果一个client和server保持一个连接的话,有多少个client接入,server就需要创建同等的线程来处理。线程上下文切换,数据同步和内存消耗,对server来说,将是非常大的开销。

代码实现

传统基于线程架构通常采用BIO的方式来实现,代码如下:

  1. public class Server implements Runnable { 
  2.  
  3.     int port; 
  4.  
  5.     public Server(int port) { 
  6.         this.port = port; 
  7.     } 
  8.  
  9.     @Override 
  10.     public void run() { 
  11.         try { 
  12.             ServerSocket serverSocket = new ServerSocket(port); 
  13.             while (true){ 
  14.                 System.out.println("等待新连接..."); 
  15.                 new Thread(new Handler(serverSocket.accept())).start(); 
  16.             } 
  17.         } catch (IOException e) { 
  18.             e.printStackTrace(); 
  19.         } 
  20.     } 
  21.  
  22.     static class Handler implements Runnable{ 
  23.  
  24.         private Socket socket; 
  25.  
  26.         public Handler(Socket socket){ 
  27.             this.socket = socket; 
  28.         } 
  29.  
  30.         @Override 
  31.         public void run() { 
  32.             try { 
  33.                 byte[] input = new byte[1024]; 
  34.  
  35.                 this.socket.getInputStream().read(input); 
  36.                 byte[] output = process(input); 
  37.                 this.socket.getOutputStream().write(output); 
  38.                 this.socket.getOutputStream().flush(); 
  39.                 this.socket.close(); 
  40.                 System.out.println("响应完成!"); 
  41.             } catch (IOException e) { 
  42.                 e.printStackTrace(); 
  43.             } 
  44.         } 
  45.  
  46.         private byte[] process(byte[] input) { 
  47.             System.out.println("读取内容:" + new String(input)); 
  48.             return input; 
  49.         } 
  50.     } 
  51.  
  52.     public static void main(String[] args) throws InterruptedException { 
  53.         Thread thread = new Thread(new Server(2021)); 
  54.         thread.setDaemon(true); 
  55.         thread.start(); 
  56.  
  57.         synchronized (Server.class) { 
  58.             Server.class.wait(); 
  59.         } 
  60.     } 

为了避免线程创建销毁的开销,我们通常会采用线程池,但是同样也有很大的弊端:

  • 同步阻塞IO,读写阻塞,线程等待时间过长
  • 在制定线程策略的时候,只能根据CPU的数目来限定可用线程资源,不能根据连接并发数目来制定,也就是连接有限制。否则很难保证对客户端请求的高效和公平。
  • 多线程之间的上下文切换,造成线程使用效率并不高,并且不易扩展
  • 状态数据以及其他需要保持一致的数据,需要采用并发同步控制

应用场景

既然传统基于线程架构弊端这么多,它存在还有什么价值?它的应用场景是什么?

传统基于线程架构适用于连接数目比较小且一次传输大量数据的场景,比如上传,下载。

事件驱动架构

事件驱动架构:可以把线程和连接解耦,线程只用于执行事件注册的回调函数。事件驱动架构由事件生产者和事件消费者组成,前者是事件的来源,它只负责监听哪些事件发生;后者是直接处理事件或者事件发生时,响应事件的实体。

Reactor模式

什么是Reactor模式?

Reactor模式是事件驱动架构的一种具体实现方法,简而言之,就是一个单线程进行循环监听就绪IO事件,并将就绪IO事件分发给对应的回调函数。

Reactor模式由什么组成的?

Reactor模式分为两个重要组成部分,Reactor和Handler。 Reactor(反应器):循环监听就绪IO事件,并分发给回调函数。 Handler(回调函数):执行对应IO事件的实际业务逻辑。

Reactor模式解决什么问题?

反应器模式可以实现同步的多路复用,同步是指按照事件到达的顺序分发处理。反应器 接收来自不同的客户端的消息、请求和连接,尽管客户端是并发的,但是反应器可以按照事件到达的顺序触发回调函数。因此,Reactor模式将连接和线程解耦,不需要为每个连接创建单独线程。这个问题和C10K问题相同,提供了一个解决思路。

Reactor模式下的三种模型

单线程模型:IO事件轮询,分发(accept)和IO事件执行(read,decode,compute,encode,send)都在一个线程中完成,如下图所示:

在单线程模型下,不仅IO操作在Reactor线程上,而非IO操作(handlder中process()方法)也在Reactor线程上执行了,当非IO操作执行慢的话,这会大大延迟IO请求响应,所以应该把非IO操作拆出来,来加速Reactor线程对IO请求响应,就出现多线程模型。

单线程模型实现:

  1. // reactor 
  2. public class Reactor implements Runnable { 
  3.  
  4.     int port; 
  5.     Selector selector; 
  6.     ServerSocketChannel serverSocket; 
  7.  
  8.     public Reactor(int port) throws IOException { 
  9.         this.port = port; 
  10.         // 创建serverSocket对象 
  11.         serverSocket = ServerSocketChannel.open(); 
  12.         // 绑定端口 
  13.         serverSocket.socket().bind(new InetSocketAddress(port)); 
  14.         // 配置非阻塞 
  15.         serverSocket.configureBlocking(false); 
  16.         // 创建selector对象 
  17.         selector = Selector.open(); 
  18.         // serversocket注册到selector上,帮忙监听accpet事件 
  19.         serverSocket.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(serverSocket,selector)); 
  20.         /** 还可以使用 SPI provider,来创建selector和serversocket对象 
  21.         SelectorProvider p = SelectorProvider.provider(); 
  22.         selector = p.openSelector(); 
  23.         serverSocket = p.openServerSocketChannel(); 
  24.         */ 
  25.     } 
  26.  
  27.     @Override 
  28.     public void run() { 
  29.         try { 
  30.             while (!Thread.interrupted()) { 
  31.                 System.out.println("start select event..."); 
  32.                 selector.select(); 
  33.                 Set selectedKeys = selector.selectedKeys(); 
  34.                 Iterator it = selectedKeys.iterator(); 
  35.                 while (it.hasNext()) { 
  36.                     dispatch((SelectionKey)it.next()); 
  37.                 } 
  38.                 selectedKeys.clear(); 
  39.             } 
  40.         } catch (IOException e) { 
  41.             e.printStackTrace(); 
  42.         } 
  43.     } 
  44.  
  45.     private void dispatch(SelectionKey key) { 
  46.         Runnable r = (Runnable) key.attachment(); 
  47.         if (r != null) { 
  48.             r.run(); 
  49.         } 
  50.     } 
  51.  
  52.  
  53.     public static void main(String[] args) throws IOException, InterruptedException { 
  54.         Thread thread = new Thread(new Reactor(2021)); 
  55.         thread.start(); 
  56.         synchronized (Reactor.class) { 
  57.             Reactor.class.wait(); 
  58.         } 
  59.     } 
  60. // acceptor调度器 
  61. public class Acceptor implements Runnable { 
  62.  
  63.     ServerSocketChannel serverSocket; 
  64.     Selector selector; 
  65.  
  66.     public Acceptor(ServerSocketChannel serverSocket,Selector selector) { 
  67.         this.serverSocket = serverSocket; 
  68.         this.selector = selector; 
  69.     } 
  70.  
  71.     @Override 
  72.     public void run() { 
  73.         try { 
  74.             SocketChannel socket = this.serverSocket.accept(); 
  75.             if (socket != null) { 
  76.                 new Handler(selector,socket); 
  77.             } 
  78.  
  79.         } catch (IOException e) { 
  80.             e.printStackTrace(); 
  81.         } 
  82.     } 
  83. // 回调函数handler 
  84. public class Handler implements Runnable { 
  85.  
  86.     Selector selector; 
  87.     SocketChannel socket; 
  88.     SelectionKey sk; 
  89.  
  90.     ByteBuffer input = ByteBuffer.allocate(1024); 
  91.     ByteBuffer output = ByteBuffer.allocate(1024); 
  92.     static final int READING = 0, SENDING = 1; 
  93.     int state = READING; 
  94.  
  95.  
  96.     public Handler(Selector selector, SocketChannel socket) throws IOException { 
  97.         this.selector = selector; 
  98.         this.socket = socket; 
  99.  
  100.         this.socket.configureBlocking(false); 
  101.         sk = this.socket.register(selector,0); 
  102.         sk.attach(this); 
  103.         sk.interestOps(SelectionKey.OP_READ); 
  104.         selector.wakeup(); 
  105.     } 
  106.  
  107.     @Override 
  108.     public void run() { 
  109.         try{ 
  110.             if (state == READING) { 
  111.                 read(); 
  112.             } else if (state == SENDING) { 
  113.                 send(); 
  114.             } 
  115.         } catch (IOException ex) { 
  116.             ex.printStackTrace(); 
  117.         } 
  118.     } 
  119.  
  120.     private void read() throws IOException { 
  121.         socket.read(input); 
  122.         if (inputIsComplete()) { 
  123.             // 执行业务逻辑代码 
  124.             process(); 
  125.             state = SENDING; 
  126.             // Normally also do first write now 
  127.             sk.interestOps(SelectionKey.OP_WRITE); 
  128.         } 
  129.     } 
  130.  
  131.     private void send() throws IOException { 
  132.         socket.write(output); 
  133.         socket.close(); 
  134.         if (outputIsComplete()) sk.cancel(); 
  135.     } 
  136.  
  137.     boolean inputIsComplete() { return true;} 
  138.  
  139.     boolean outputIsComplete() {return true;} 
  140.     // 处理非IO操作(业务逻辑代码) 
  141.     void process(){ 
  142.         String msg = new String(input.array()); 
  143.         System.out.println("读取内容:" + msg); 
  144.         output.put(msg.getBytes()); 
  145.         output.flip(); 
  146.     } 
  • 多线程模型:与单线程模型不同的是添加一个业务线程池,将非IO操作(业务逻辑处理)交给业务线程池来处理,提高Reactor线程的IO响应,如图所示:

 

在多线程模型下,虽然将非IO操作拆出去了,但是所有IO操作都在Reactor单线程中完成的。在高负载、高并发场景下,也会成为瓶颈,于是对Reactor单线程进行了优化,出现了主从线程模型。

多线程模型实现:

  1. public class Reactor implements Runnable { 
  2.  
  3.     int port; 
  4.     Selector selector; 
  5.     ServerSocketChannel serverSocket; 
  6.  
  7.  
  8.     public Reactor(int port) throws IOException { 
  9.         this.port = port; 
  10.  
  11.         // 创建serverSocket对象 
  12.         serverSocket = ServerSocketChannel.open(); 
  13.         // 绑定端口 
  14.         serverSocket.socket().bind(new InetSocketAddress(port)); 
  15.         // 配置非阻塞 
  16.         serverSocket.configureBlocking(false); 
  17.  
  18.         // 创建selector对象 
  19.         selector = Selector.open(); 
  20.         // serversocket注册到selector上,帮忙监听accpet事件 
  21.         serverSocket.register(selector, SelectionKey.OP_ACCEPT, new Acceptor("Acceptor",serverSocket,selector)); 
  22.  
  23.         /** 还可以使用 SPI provider,来创建selector和serversocket对象 
  24.         SelectorProvider p = SelectorProvider.provider(); 
  25.         selector = p.openSelector(); 
  26.         serverSocket = p.openServerSocketChannel(); 
  27.         */ 
  28.     } 
  29.  
  30.     @Override 
  31.     public void run() { 
  32.         try { 
  33.             while (!Thread.interrupted()) { 
  34.                 System.out.println("start select event..."); 
  35.                 selector.select(); 
  36.                 Set selectedKeys = selector.selectedKeys(); 
  37.                 Iterator it = selectedKeys.iterator(); 
  38.                 while (it.hasNext()) { 
  39.                     dispatch((SelectionKey)it.next()); 
  40.                 } 
  41.                 selectedKeys.clear(); 
  42.             } 
  43.         } catch (IOException e) { 
  44.             e.printStackTrace(); 
  45.         } 
  46.     } 
  47.  
  48.     private void dispatch(SelectionKey key) { 
  49.         SelfRunable r = (SelfRunable) key.attachment(); 
  50.         if (r != null) { 
  51.             System.out.println("dispatch to " + r.getName() + "===="); 
  52.             r.run(); 
  53.         } 
  54.     } 
  55.  
  56.  
  57.     public static void main(String[] args) throws IOException, InterruptedException { 
  58.  
  59.         Thread thread = new Thread(new Reactor(2021)); 
  60.         thread.start(); 
  61.  
  62.         synchronized (Reactor.class) { 
  63.             Reactor.class.wait(); 
  64.         } 
  65.  
  66.  
  67.     } 
  68.  
  69. public class Acceptor implements SelfRunable { 
  70.     ServerSocketChannel serverSocket; 
  71.     Selector selector; 
  72.     String name
  73.     public Acceptor(String name, ServerSocketChannel serverSocket,Selector selector) { 
  74.         this.name = name
  75.         this.serverSocket = serverSocket; 
  76.         this.selector = selector; 
  77.     } 
  78.  
  79.     @Override 
  80.     public void run() { 
  81.         try { 
  82.             SocketChannel socket = this.serverSocket.accept(); 
  83.             if (socket != null) { 
  84.                 new Handler("handler_" + ((InetSocketAddress)socket.getLocalAddress()).getPort(), selector,socket); 
  85.             } 
  86.  
  87.         } catch (IOException e) { 
  88.             e.printStackTrace(); 
  89.         } 
  90.     } 
  91.  
  92.     @Override 
  93.     public String getName() { 
  94.         return this.name
  95.     } 
  96.  
  97. public class Handler implements SelfRunable { 
  98.     String name
  99.     Selector selector; 
  100.     SocketChannel socket; 
  101.     SelectionKey sk; 
  102.     ByteBuffer input = ByteBuffer.allocate(1024); 
  103.     ByteBuffer output = ByteBuffer.allocate(1024); 
  104.     static final int READING = 0, SENDING = 1,  PROCESSING = 3; 
  105.     volatile int state = READING; 
  106.     static ExecutorService poolExecutor = Executors.newFixedThreadPool(5); 
  107.  
  108.     public Handler(String name, Selector selector, SocketChannel socket) throws IOException { 
  109.         this.selector = selector; 
  110.         this.socket = socket; 
  111.         this.name = name
  112.  
  113.         this.socket.configureBlocking(false); 
  114.         sk = this.socket.register(selector,0); 
  115.         sk.attach(this); 
  116.         sk.interestOps(SelectionKey.OP_READ); 
  117.         selector.wakeup(); 
  118.     } 
  119.  
  120.     @Override 
  121.     public void run() { 
  122.         try{ 
  123.             System.out.println("state:" + state); 
  124.             if (state == READING) { 
  125.                 read(); 
  126.             } else if (state == SENDING) { 
  127.                 send(); 
  128.             } 
  129.         } catch (IOException ex) { 
  130.             ex.printStackTrace(); 
  131.         } 
  132.     } 
  133.  
  134.     synchronized void read() throws IOException { 
  135.         socket.read(input); 
  136.         if (inputIsComplete()) { 
  137.             state = PROCESSING; 
  138.            poolExecutor.execute(new Processer()); 
  139.         } 
  140.     } 
  141.  
  142.     synchronized void processAndHandOff() { 
  143.         System.out.println("processAndHandOff========="); 
  144.         process(); 
  145.         state = SENDING; // or rebind attachment 
  146.         sk.interestOps(SelectionKey.OP_WRITE); 
  147.         selector.wakeup(); 
  148.         System.out.println("processAndHandOff finish ! ========="); 
  149.     } 
  150.  
  151.     private void send() throws IOException { 
  152.         System.out.println("start send ..."); 
  153.         socket.write(output); 
  154.         socket.close(); 
  155.         System.out.println("start send finish!"); 
  156.         if (outputIsComplete()) sk.cancel(); 
  157.     } 
  158.  
  159.     boolean inputIsComplete() { return true;} 
  160.  
  161.     boolean outputIsComplete() {return true;} 
  162.  
  163.     void process(){ 
  164.         String msg = new String(input.array()); 
  165.         System.out.println("读取内容:" + msg); 
  166.         output.put(msg.getBytes()); 
  167.         output.flip(); 
  168.     } 
  169.  
  170.     @Override 
  171.     public String getName() { 
  172.         return this.name
  173.     } 
  174.  
  175.     class Processer implements Runnable { 
  176.         public void run() { processAndHandOff(); } 
  177.     } 
  • 主从线程模型: 相比多线程模型而言,对于多核cpu,为了充分利用资源,将Reactor拆分成了mainReactor 和 subReactor,但是,主从线程模型也有弊端,不适合大量数据传输。 mainReactor:负责监听接收(accpet)新连接,将新连接后续操作交给subReactor来处理,通常由一个线程处理。 subReactor: 负责处理IO的读写操作,通常由多个线程处理。 非IO操作依然由业务线程池来处理。

主从线程模型实现:

  1. public class Reactor implements Runnable { 
  2.  
  3.     int port; 
  4.     Selector selector; 
  5.     ServerSocketChannel serverSocket; 
  6.     int SUBREACTOR_SIZE = 1; 
  7.     SubReactor[] subReactorPool = new SubReactor[SUBREACTOR_SIZE]; 
  8.  
  9.  
  10.     public Reactor(int port) throws IOException { 
  11.         this.port = port; 
  12.  
  13.         // 创建serverSocket对象 
  14.         serverSocket = ServerSocketChannel.open(); 
  15.         // 绑定端口 
  16.         serverSocket.socket().bind(new InetSocketAddress(port)); 
  17.         // 配置非阻塞 
  18.         serverSocket.configureBlocking(false); 
  19.  
  20.         // 创建selector对象 
  21.         selector = Selector.open(); 
  22.         // serversocket注册到selector上,帮忙监听accpet事件 
  23.         serverSocket.register(selector, SelectionKey.OP_ACCEPT, new Acceptor("Acceptor",serverSocket,subReactorPool)); 
  24.  
  25.         // 初始化subreactor pool 
  26.         initSubReactorPool(); 
  27.  
  28.  
  29.         /** 还可以使用 SPI provider,来创建selector和serversocket对象 
  30.         SelectorProvider p = SelectorProvider.provider(); 
  31.         selector = p.openSelector(); 
  32.         serverSocket = p.openServerSocketChannel(); 
  33.         */ 
  34.     } 
  35.  
  36.     @Override 
  37.     public void run() { 
  38.         try { 
  39.             while (!Thread.interrupted()) { 
  40.                 System.out.println("mainReactor start select event..."); 
  41.                 selector.select(); 
  42.                 Set selectedKeys = selector.selectedKeys(); 
  43.                 Iterator it = selectedKeys.iterator(); 
  44.                 while (it.hasNext()) { 
  45.                     dispatch((SelectionKey)it.next()); 
  46.                 } 
  47.                 selectedKeys.clear(); 
  48.             } 
  49.         } catch (IOException e) { 
  50.             e.printStackTrace(); 
  51.         } 
  52.     } 
  53.  
  54.     void initSubReactorPool() { 
  55.         try { 
  56.             for (int i = 0; i < SUBREACTOR_SIZE; i++) { 
  57.                 subReactorPool[i] = new SubReactor("SubReactor" + i); 
  58.             } 
  59.         } catch (IOException ex) { /* ... */ } 
  60.     } 
  61.  
  62.     private void dispatch(SelectionKey key) { 
  63.         SelfRunable r = (SelfRunable) key.attachment(); 
  64.         if (r != null) { 
  65.             System.out.println("mainReactor dispatch to " + r.getName() + "===="); 
  66.             r.run(); 
  67.         } 
  68.     } 
  69.  
  70.  
  71.     public static void main(String[] args) throws IOException, InterruptedException { 
  72.  
  73.         Thread thread = new Thread(new Reactor(2021)); 
  74.         thread.start(); 
  75.  
  76.         synchronized (Reactor.class) { 
  77.             Reactor.class.wait(); 
  78.         } 
  79.     } 
  80.  
  81. public class SubReactor implements SelfRunable { 
  82.  
  83.     private Selector selector; 
  84.     private String name
  85.     private List<SelfRunable> task = new ArrayList<SelfRunable>(); 
  86.  
  87.     public SubReactor(String name) throws IOException { 
  88.         this.name = name
  89.         selector = Selector.open(); 
  90.         new Thread(this).start(); 
  91.     } 
  92.  
  93.     @Override 
  94.     public String getName() { 
  95.         return this.name
  96.     } 
  97.  
  98.     @Override 
  99.     public void run() { 
  100.         try { 
  101.             while (!Thread.interrupted()) { 
  102.                 System.out.println("subReactor start select event..."); 
  103.                 selector.select(5000); 
  104.                 Set selectedKeys = selector.selectedKeys(); 
  105.                 Iterator it = selectedKeys.iterator(); 
  106.                 while (it.hasNext()) { 
  107.                     dispatch((SelectionKey)it.next()); 
  108.                 } 
  109.                 selectedKeys.clear(); 
  110.  
  111.             } 
  112.         } catch (IOException e) { 
  113.             e.printStackTrace(); 
  114.         } 
  115.     } 
  116.  
  117.     private void dispatch(SelectionKey key) { 
  118.         SelfRunable r = (SelfRunable) key.attachment(); 
  119.         if (r != null) { 
  120.             System.out.println("subReactor dispatch to " + r.getName() + "===="); 
  121.             r.run(); 
  122.         } 
  123.     } 
  124.  
  125.     public Selector getSelector(){ 
  126.         return this.selector; 
  127.     } 
  128.  
  129.     public void submit(SelfRunable runnable) { 
  130.         task.add(runnable); 
  131.     } 
  132.  
  133.  
  134. public class Acceptor implements SelfRunable { 
  135.  
  136.     int next = 0; 
  137.     String name
  138.     SubReactor[] subReactorPool; 
  139.     ServerSocketChannel serverSocket; 
  140.  
  141.     public Acceptor(String name, ServerSocketChannel serverSocket,SubReactor[] subReactorPool) { 
  142.         this.name = name
  143.         this.serverSocket = serverSocket; 
  144.         this.subReactorPool = subReactorPool; 
  145.     } 
  146.  
  147.     @Override 
  148.     public void run() { 
  149.         try { 
  150.             SocketChannel socket = this.serverSocket.accept(); 
  151.             if (socket != null) { 
  152.                 new Handler("handler", subReactorPool[next].getSelector(),socket); 
  153.             } 
  154.             if (++next == subReactorPool.length) {next=0;} 
  155.  
  156.         } catch (IOException e) { 
  157.             e.printStackTrace(); 
  158.         } 
  159.     } 
  160.  
  161.     @Override 
  162.     public String getName() { 
  163.         return this.name
  164.     } 
  165.  
  166. public class Handler implements SelfRunable { 
  167.  
  168.     String name
  169.     Selector selector; 
  170.     SocketChannel socket; 
  171.     SelectionKey sk; 
  172.  
  173.     ByteBuffer input = ByteBuffer.allocate(1024); 
  174.     ByteBuffer output = ByteBuffer.allocate(1024); 
  175.     static final int READING = 0, SENDING = 1,  PROCESSING = 3; 
  176.     volatile int state = READING; 
  177.  
  178.     static ExecutorService poolExecutor = Executors.newFixedThreadPool(5); 
  179.  
  180.     public Handler(String name, Selector selector, SocketChannel socket) throws IOException { 
  181.         this.selector = selector; 
  182.         this.socket = socket; 
  183.         this.name = name
  184.  
  185.         this.socket.configureBlocking(false); 
  186.         sk = this.socket.register(this.selector,0); 
  187.         sk.attach(this); 
  188.         sk.interestOps(SelectionKey.OP_READ); 
  189.         selector.wakeup(); 
  190.     } 
  191.  
  192.     @Override 
  193.     public void run() { 
  194.         try{ 
  195.             System.out.println("state:" + state); 
  196.             if (state == READING) { 
  197.                 read(); 
  198.             } else if (state == SENDING) { 
  199.                 send(); 
  200.             } 
  201.         } catch (IOException ex) { 
  202.             ex.printStackTrace(); 
  203.         } 
  204.     } 
  205.  
  206.     synchronized void read() throws IOException { 
  207.         socket.read(input); 
  208.         if (inputIsComplete()) { 
  209.             state = PROCESSING; 
  210.            poolExecutor.execute(new Processer()); 
  211.         } 
  212.     } 
  213.  
  214.     synchronized void processAndHandOff() { 
  215.         System.out.println("processAndHandOff========="); 
  216.         process(); 
  217.         state = SENDING; // or rebind attachment 
  218.         sk.interestOps(SelectionKey.OP_WRITE); 
  219.         selector.wakeup(); 
  220.         System.out.println("processAndHandOff finish ! ========="); 
  221.     } 
  222.  
  223.     private void send() throws IOException { 
  224.         System.out.println("start send ..."); 
  225.         socket.write(output); 
  226.         socket.close(); 
  227.         System.out.println("start send finish!"); 
  228.         if (outputIsComplete()) sk.cancel(); 
  229.     } 
  230.  
  231.     boolean inputIsComplete() { return true;} 
  232.  
  233.     boolean outputIsComplete() {return true;} 
  234.  
  235.     void process(){ 
  236.         String msg = new String(input.array()); 
  237.         System.out.println("读取内容:" + msg); 
  238.         output.put(msg.getBytes()); 
  239.         output.flip(); 
  240.     } 
  241.  
  242.     @Override 
  243.     public String getName() { 
  244.         return this.name
  245.     } 
  246.  
  247.     class Processer implements Runnable { 
  248.         public void run() { processAndHandOff(); } 
  249.     } 

Reactor线程模型演进

模型

简介

弊端

单线程模型

IO/非IO操作都在Reactor单线程中完成

非IO操作执行慢,影响IO操作响应延迟

多线程模型

拆分非IO操作交给业务线程池执行,IO操作由Reator单线程执行

高并发,高负载场景下,Reactor单线程会成为瓶颈

主从线程模型

Reactor单线程拆分为mainReactor和subReactor

不适合大量数据传输

Netty线程模型

Reactor主从线程模型-抽象模型

  • 创建ServerSocketChannel过程(创建channel,配置非阻塞)
  • ServerSocketChannel注册到mainReactor的selector对象上,监听accept事件
  • mainReactor的selector监听到新连接SocketChannel,将SocketChannel注册到subReactor的selector对象上,监听read/write事件
  • subReactor的selector监听到read/write事件,移交给业务线程池(对应netty的pipeline)

Netty线程模型

我们再好好看看mainReactor和subReactor,其实这两个类功能非常相似,所以Netty将mainReactor和subReactor统一成了EventLoop。对于Netty零基础的,请参考这个Reactor主从线程模型-抽象模型和下面这张图来理解EventLoop。