Netty 搭建简单的http服务
- Netty 简介
- 代码展示
- netty 依赖
- NettyServer netty 服务端启动类
- MyChannelInitializer 设置编码解码器,并添加自己的业务方法
- MyClientHandler 实现自己的业务方法。主要方法 是读取到数据后处理
- 效果展示
- 服务端打印截图
- 采用Postman 测试 截图
Netty 简介
首先netty是什么,官网是这样定义的。
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
Netty是一个异步事件驱动的网络应用程序框架用于快速开发可维护的高性能协议服务器和客户端。
Netty是目前所有NIO框架中性能最好的框架,Java本身提供的有NIO工具,但是在实际操作过程中,复杂繁琐,且对编程人员要求比较高,多线程环境下不容易定位问题,且容易出现问题,所以netty的出现极大的简化了这种操作,且性能稳定高效,其架构设计也非常优秀,值得深入学习总结。
netty官网:https://netty.io/
代码展示
netty 依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.36.Final</version>
</dependency>
NettyServer netty 服务端启动类
public static void main(String[] args) {
new NettyServer().bing(8082);
}
private void bing(int port) {
//配置服务端NIO线程组
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class)//非阻塞模式
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new MyChannelInitializer());
ChannelFuture future = bootstrap.bind(port).sync();
System.out.println("hello ,server is start up");
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
MyChannelInitializer 设置编码解码器,并添加自己的业务方法
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//数据解码操作
socketChannel.pipeline().addLast(new HttpResponseEncoder());
//数据编码操作
socketChannel.pipeline().addLast(new HttpRequestDecoder());
//在管道中添加自己的业务方法
socketChannel.pipeline().addLast(new MyClientHandler());
}
}
MyClientHandler 实现自己的业务方法。主要方法 是读取到数据后处理
public class MyClientHandler extends ChannelInboundHandlerAdapter {
public void channelRead(ChannelHandlerContext context,Object msg){
if (msg instanceof HttpRequest){
DefaultHttpRequest request=(DefaultHttpRequest)msg;
System.out.println("URI: "+request.uri());
System.out.println(msg);
}
if (msg instanceof HttpContent){
LastHttpContent content=(LastHttpContent) msg;
ByteBuf byteBuf=content.content();
if (!(byteBuf instanceof EmptyByteBuf)){
//接收msg消息
byte[]msgByte=new byte[byteBuf.readableBytes()];
byteBuf.readBytes(msgByte);
System.out.println(new String(msgByte,Charset.forName("UTF-8")));
}
}
String sendMsg = "hello ni hao,这是netty -respondse 返回的信息.";
FullHttpResponse response=new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,
Unpooled.wrappedBuffer(sendMsg.getBytes(Charset.forName("UTF-8")))
);
//返回值类型
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
//返回值的大小
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
//返回值 保持长连接
response.headers().set(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);
context.write(response);
context.flush();
}
public void channelReadComplete(ChannelHandlerContext context){
context.flush();
}
public void exceptionCaught(ChannelHandlerContext context,Throwable c){
context.close();
c.printStackTrace();
}