背景
Spring Boot 给开发者带来了极大的便利,以至于我们开发一个项目的时候,首先想到的就是 它,然后服务器也不加死锁的使用了它默认内置 Tomcat,甚至都不会去考虑下 是否需要切换 jetty ?
高并发、大流量的今天,我们是否还有其他的 服务端处理并发请求的选择的?
答案当然是肯定的,本节 我们就先来搭建一个 Web Netty 的demo,后面再细细研究,这也符合我们学习一个新技术的思路:先学会怎么用,再去慢慢debug 。
概述
netty 官网:
netty 是什么?
Netty is an asynchronous event-driven network application framework for rapid development of maintainable high performance protocol servers & clients.
Netty是异步事件驱动的网络应用程序框架 用于快速开发可维护的高性能协议服务器和客户端。
最新版本:
Netty 4.1.45.Final released on 2020.01.30
搭建项目步骤:
1、idea 创建一个Maven 项目,并加入 最新版的 netty 版本依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.45.Final</version>
</dependency>
netty-all 表示引入netty 所有相关依赖
2、编写服务端处理类
TestServer.class
public class TestServer {
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
TestServerInitializer.class
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());
}
}
TestHttpServerHandler.class
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpRequest) {
HttpRequest request = (HttpRequest) httpObject;
System.out.println(request.uri());
System.out.println(request.method());
ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
channelHandlerContext.writeAndFlush(response);
}
}
}
启动 TestServer 主服务类~~~
客户端发起 GET 请求
$ curl localhost:8899/
可以看到控制台打印的日志~~~~~
是不是很惊喜,一个简单的 DEMO 运行起来。对于发起请求方来说,后端的服务毫无感知。
实际上,Netty 的范式编程 主要步骤也是如上。
后面我们再深入一步的再分析~~~~~~~
网友评论