【发布时间】:2016-01-18 07:07:05
【问题描述】:
我正在尝试将“缩略图生成器”实现为微服务。我认为这样的东西可能最适合作为 TCP 服务器,因此在简要调查了一些选项后,我选择了 Netty。为了使服务尽可能节省内存,我宁愿避免将完整图像加载到内存中,因此一直在尝试构建一个管道,其“ThumbnailHandler”可以使用管道流来利用 Netty 的分块读取,以便随着 Netty 接收到更多字节,缩略图生成器可以遍历更多的流。不幸的是,我一般对 Netty 或 NIO 模式不够熟悉,不知道我是否会以最好的方式来解决这个问题,而且我什至无法让简化的版本像我预期的那样工作。
这是我的服务器设置:
public class ThumbnailerServer {
private int port;
public ThumbnailerServer(int port) {
this.port = port;
}
public void run() throws Exception {
final ThreadFactory acceptFactory = new DefaultThreadFactory("accept");
final ThreadFactory connectFactory = new DefaultThreadFactory("connect");
final NioEventLoopGroup acceptGroup = new NioEventLoopGroup(1, acceptFactory, NioUdtProvider.BYTE_PROVIDER);
final NioEventLoopGroup connectGroup = new NioEventLoopGroup(0, connectFactory, NioUdtProvider.BYTE_PROVIDER);
try {
ServerBootstrap b = new ServerBootstrap();
b.group(acceptGroup, connectGroup)
.channelFactory(NioUdtProvider.BYTE_ACCEPTOR)
.option(ChannelOption.SO_BACKLOG, 128)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<UdtChannel>() {
@Override
public void initChannel(UdtChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast("handler", new ThumbnailerServerHandler());
}
});
// bind and start to accept incoming connections.
b.bind(port).sync().channel().closeFuture().sync();
} finally {
connectGroup.shutdownGracefully();
acceptGroup.shutdownGracefully();
}
}
}
还有缩略图处理程序:
public class ThumbnailerServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
private static final Logger logger = LoggerFactory.getLogger(ThumbnailerServerHandler.class);
private PipedInputStream toThumbnailer = new PipedInputStream();
private PipedOutputStream fromClient = new PipedOutputStream(toThumbnailer);
private static final ListeningExecutorService executor = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(5));
private ListenableFuture<OutputStream> future;
public ThumbnailerServerHandler() throws IOException {
super(ByteBuf.class, true);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
future = executor.submit(() -> ThumbnailGenerator.generate(toThumbnailer));
future.addListener(() -> {
try {
ctx.writeAndFlush(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, executor);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
this.fromClient.close();
this.toThumbnailer.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
int readableBytes = msg.readableBytes();
msg.readBytes(this.fromClient, readableBytes);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Encountered error during communication", cause);
ctx.close();
}
}
这是我简化的“缩略图”,直到我完成整个流程:
public class ThumbnailGenerator {
public static OutputStream generate(InputStream toThumbnailer) {
OutputStream stream = new ByteArrayOutputStream();
try {
IOUtils.copy(toThumbnailer, stream);
} catch (IOException e) {
e.printStackTrace();
}
return stream;
}
}
- 像这样在 handlerAdded 方法中剥离异步任务是否合适?有没有更“简洁”的方式来做到这一点?
- IOUtils.copy 应该并且会阻塞(由于对管道输入流的读取),直到有数据可供读取,这就是为什么我将其卸载到执行程序池中,因为我无法在处理程序中阻塞如果我想继续接收字节。但是,我发现这永远不会完成,但它确实取得了进展。那是因为我从未遇到过 EOF 字节(-1)吗?我怎样才能使这个流程发挥作用?
- 我是否缺少 netty 中可以简化此过程的构造?我曾考虑将它实现为一个解码器,在它拥有整个流之前不会解码,但随后我会将所有内容加载到内存中。
【问题讨论】: