netty处理http文件上传
2020-09-25 本文已影响0人
大侠陈
导入 netty-all-4.1.45.Final.jar 包
实现一个FileUploadRequestHandler类,继承自SimpleChannelInboundHandler<FullHttpRequest>
public static class FileUploadRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
HttpDataFactory factory = new DefaultHttpDataFactory(true);
HttpPostRequestDecoder httpDecoder = new HttpPostRequestDecoder(factory, fullHttpRequest);
httpDecoder.setDiscardThreshold(0);
final HttpContent chunk = fullHttpRequest;
httpDecoder.offer(chunk);
if (chunk instanceof LastHttpContent) {
List<InterfaceHttpData> interfaceHttpDataList = httpDecoder.getBodyHttpDatas();
for (InterfaceHttpData data : interfaceHttpDataList) {
if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
FileUpload fileUpload = (FileUpload) data;
try( FileOutputStream fileOutputStream = new FileOutputStream("netty_pic.png") ) {
fileOutputStream.write(fileUpload.get());
fileOutputStream.flush();
}
}
//如果数据类型为参数类型,则保存到body对象中
if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute){
Attribute attribute = (Attribute) data;
System.out.println(attribute.getName() + ":" + attribute.getValue());
}
}
}
FullHttpResponse response = new DefaultFullHttpResponse(
io.netty.handler.codec.http.HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8));
response.headers().set("Content-Type", "text/plain");
response.headers().set("Content-Length", response.content().readableBytes());
channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
}
启动服务器
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup(2);
ServerBootstrap serverBootstrap = new ServerBootstrap();
try {
serverBootstrap
.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast( new HttpServerCodec());
ch.pipeline().addLast(new HttpObjectAggregator(1024 * 1024));
ch.pipeline().addLast(new HttpServerExpectContinueHandler());
ch.pipeline().addLast(new HttpRequestHandler());
}
});
ChannelFuture future = serverBootstrap.bind(8088).sync();
future.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
注意
EventLoopGroup boss = new NioEventLoopGroup(1);
EventLoopGroup worker = new NioEventLoopGroup(2);
这是两个线程池,第一处理网络连接的建立,第二个处理网络IO读写,使用时可以根据自己的需求调整,但是不建议将这两个值设的很多,业务处理的线程池建议和网络线程隔离开。