導(dǎo)入 netty-all-4.1.45.Final.jar 包
實(shí)現(xiàn)一個(gè)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();
}
}
//如果數(shù)據(jù)類型為參數(shù)類型,則保存到body對(duì)象中
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);
}
}
啟動(dòng)服務(wù)器
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);
這是兩個(gè)線程池成肘,第一處理網(wǎng)絡(luò)連接的建立,第二個(gè)處理網(wǎng)絡(luò)IO讀寫拭抬,使用時(shí)可以根據(jù)自己的需求調(diào)整占业,但是不建議將這兩個(gè)值設(shè)的很多,業(yè)務(wù)處理的線程池建議和網(wǎng)絡(luò)線程隔離開赦肋。