Netty打开选择器Selector时, 会打开管道Pipe(单向管道)(主要用于单向数据传输)
Pipe管道由一对通道组成, 可写接收通道(writable sink channel)和可读源通道(readable source channel), 以便按顺序传输数据
// Pipe例子
Pipe pipe = Pipe.open();
Pipe.SinkChannel sinkChannel = pipe.sink();
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(43);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
sinkChannel.write(buf);
}
Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf1 = ByteBuffer.allocate(43);
sourceChannel.read(buf1);
System.out.println(new String(buf1.array(), StandardCharsets.UTF_8));
PipeImpl代码结构
// 管道现实者
class PipeImpl extends Pipe {
...
// 管道私有化类, 负责管道初始化并失败重试机制
private class Initializer implements PrivilegedExceptionAction<Void> {
...
// 回环连接器, 实现sinkchannel+sourcechannel通道
private class LoopbackConnector implements Runnable {
...
}
}
Pipe的实现也是通过SPI的提供者模式选择管道实现者PipeImpl, 以方便分离实现与调用之间的耦合度
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。