java nio 使用 reactor 模式处理高并发,核心在于将网络 i/o 操作与业务逻辑处理分离,通过单线程或线程池管理多个 channel 的 i/o 事件。具体做法是创建一个主 reactor 线程负责监听新连接并分发任务,以及一个或多个从 reactor 线程池负责已建立连接的读写操作,从而避免阻塞调用导致的高并发性能瓶颈。

Reactor 模式如何分发新连接请求
Reactor 模式通过多路复用器(Selector)轮询就绪事件来分发新连接。当有新连接到达时,Selector 检测到 ACCEPT 事件,主 Reactor 线程接受该连接并将其注册到负责读写的 Selector 上,随后触发 READ 事件由工作线程处理后续数据。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class ReactorServer {
private final Selector selector;
private final ServerSocketChannel serverChannel;
public ReactorServer(int port) throws IOException {
this.selector = Selector.open();
this.serverChannel = ServerSocketChannel.open();
this.serverChannel.configureBlocking(false);
this.serverChannel.bind(new InetSocketAddress(port));
// 注册 ACCEPT 事件
this.serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void run() throws IOException {
while (true) {
int readyCount = selector.select();
if (readyCount == 0) continue;
Set<selectionkey> selectedKeys = selector.selectedKeys();
Iterator<selectionkey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
handleAccept(key);
} else if (key.isReadable()) {
handleRead(key);
}
}
}
}
private void handleAccept(SelectionKey key) throws IOException {
SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
clientChannel.configureBlocking(false);
// 将新连接注册到同一个 Selector 监听 READ 事件
clientChannel.register(selector, SelectionKey.OP_READ);
}
private void handleRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
// 实际业务中应使用 ByteBuffer 读取数据
System.out.println("Received data from client");
}
public static void main(String[] args) throws IOException {
new ReactorServer(8080).run();
}
}</selectionkey></selectionkey>
如何确保读写操作不阻塞主线程
通过将非阻塞 Channel 的读写操作绑定到独立的线程池或使用异步回调机制,确保主 Reactor 线程仅负责事件分发而不执行耗时的 I/O 读写。在 Java NIO 中,通常将 READ/WRITE 事件的处理逻辑提交给工作线程池,或者在主线程中快速完成数据拷贝后交由业务线程处理。
KeystoneJS 是一个功能强大的开源无头 CMS,适用于 Node.js,它根据您的模式定义自动生成 GraphQL API 和基于 React 的管理界面。由 Thinkmill 构建,支持 PostgreSQL 和 SQLite、自定义访问控制、钩子、虚拟字段和基于文档的富文本编辑。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadedReactorServer {
private final Selector selector;
private final ServerSocketChannel serverChannel;
private final ExecutorService workerPool;
public ThreadedReactorServer(int port, int threadCount) throws IOException {
this.selector = Selector.open();
this.serverChannel = ServerSocketChannel.open();
this.serverChannel.configureBlocking(false);
this.serverChannel.bind(new InetSocketAddress(port));
this.serverChannel.register(selector, SelectionKey.OP_ACCEPT);
// 创建线程池处理读写业务
this.workerPool = Executors.newFixedThreadPool(threadCount);
}
public void run() throws IOException {
while (true) {
int readyCount = selector.select();
if (readyCount == 0) continue;
Set<selectionkey> selectedKeys = selector.selectedKeys();
Iterator<selectionkey> iterator = selectedKeys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (key.isAcceptable()) {
handleAccept(key);
} else if (key.isReadable()) {
// 提交读写任务到线程池,避免阻塞 Selector 循环
workerPool.submit(() -> handleRead(key));
}
}
}
}
private void handleAccept(SelectionKey key) throws IOException {
SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept();
clientChannel.configureBlocking(false);
clientChannel.register(selector, SelectionKey.OP_READ);
}
private void handleRead(SelectionKey key) {
try {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer); // 非阻塞读取
// 模拟耗时业务处理
processBusinessLogic(buffer.array());
} catch (IOException e) {
e.printStackTrace();
}
}
private void processBusinessLogic(byte[] data) {
// 模拟业务逻辑
System.out.println("Processing data: " + new String(data));
}
public static void main(String[] args) throws IOException {
new ThreadedReactorServer(8080, 4).run();
}
}</selectionkey></selectionkey>
如何处理单个连接上的多次读写事件
对于单个连接上的多次读写事件,Reactor 模式依赖 SelectionKey 的状态保持和 Selector 的持续轮询。每次读写完成后,如果仍有数据需要处理或连接保持活跃,需重新注册相应的 OP_READ 或 OP_WRITE 事件,确保 Selector 能继续捕获该 Channel 的后续状态变化。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










