1、pom
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.75.Final</version>
</dependency>
2、SimpleHttpServerHandler
package com.example.demo.http;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@Slf4j
public class SimpleHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
try {
log.info("SimpleHttpServerHandler receive fullHttpRequest=" + fullHttpRequest);
String result = doHandle(fullHttpRequest);
log.info("SimpleHttpServerHandler,result=" + result);
byte[] responseBytes = result.getBytes(StandardCharsets.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, HttpResponseStatus.OK,
Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().setInt("Content-Length", response.content().readableBytes());
boolean isKeepAlive = HttpUtil.isKeepAlive(response);
if (!isKeepAlive) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set("Connection", "keep-alive");
ctx.write(response);
}
} catch (Exception e) {
log.error("channelRead0 exception,", e);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
/**
* 实际处理
*
* @param fullHttpRequest HTTP请求参数
* @return
*/
private String doHandle(FullHttpRequest fullHttpRequest) {
if (HttpMethod.GET == fullHttpRequest.method()) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(fullHttpRequest.uri());
Map<String, List<String>> params = queryStringDecoder.parameters();
return JSON.toJSONString(params);
} else if (HttpMethod.POST == fullHttpRequest.method()) {
byte[] bytes = new byte[fullHttpRequest.content().readableBytes()];
fullHttpRequest.content().readBytes(bytes);
return new String(bytes, CharsetUtil.UTF_8);
}
return fullHttpRequest.method().name();
}
}
3、httpserver
package com.example.demo.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NettyHttpServer {
/**
* host
*/
private final static String host = "127.0.0.1";
/**
* 端口号
*/
private final static Integer port = 8085;
public static void main(String[] args) {
start();
}
/**
* netty服务端启动方法
*/
public static void start() {
log.info("SimpleHttpServer start begin ");
EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(1);
EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossEventLoopGroup, workerEventLoopGroup)
.channel(NioServerSocketChannel.class)
//开启tcp nagle算法
.childOption(ChannelOption.TCP_NODELAY, true)
//开启长连接
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel c) {
c.pipeline().addLast(new HttpServerCodec())
.addLast(new HttpObjectAggregator(512 * 1024))
.addLast(new SimpleHttpServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync();
log.info("SimpleHttpServer start at port " + port);
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
log.error("SimpleHttpServer start exception,", e);
} finally {
log.info("SimpleHttpServer shutdown bossEventLoopGroup&workerEventLoopGroup gracefully");
bossEventLoopGroup.shutdownGracefully();
workerEventLoopGroup.shutdownGracefully();
}
}
}