20190825_Netty简介

Netty定义

Netty官网的第一句话就对Netty有了一个清晰的定义:

Netty is an asynchronous event-driven network application
framework.

Netty是以异步事件驱动的网络框架。Netty之所以高效,主要来自于它是如何实现异步事件驱动的:其 I/O 模型和线程处理模型,前者决定如何收发数据,后者决定如何处理数据。

Netty架构

netty架构是基于 Reactor责任链模式(netty通过popeline将handler组装起来,通过向pipeline里添加handler来监听处理发生的事件)进行设计的。同时设计者在设计时使用了Staged Event Driven Architecture(阶段性的事件驱动架构)的思想,其思路:每个请求分为若干个阶段,每个阶段可以配置不同的线程。

Netty体系结构图

在这里插入图片描述

core(核心模块):Extensible Event Model(可扩展的事件模型),Universal Communication API(通用的通讯API),Zero-Copy-Capable Rich Byte Buffer(零拷贝的字节缓冲区)
Transport Services(传输服务): Socket & Datagram,HTTp Tunnel,In-Vm Pipe
Protocol Support(协议支持): HTTP & WebSocket,SSl.StartTLS,Google Protobuf,zlib/gzip Compression,Large File Transfer,RTSP(和流媒体有关),Legacy Text.Binary Protocols with Unit Testability

Netty的一点思考

高性能server要解决的问题

1、异步socket
2、异步IO
3、多协议支持(传输层之上)
4、减少内存碎片
5、减少锁的影响

netty的解决方案

1、使用java的nio,最好是aio(内核直接支持)
2、封装了promise,实现了基于回调的异步io
3、架构上区分了reactor层、pipeline层、协议层和逻辑层, 其协议层支持protobuf, websocket, http等
4、封装了ByteBuf,自己来管理内存,而不是完全依赖jvm 5、单个socket只在一个线程上处理、避免不必要的线程调度开销

一个栗子

public class TestServer{
    public static void main(String[] args) throws Exception{
        // boss和worker, boss分发给worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
                    childHandler(new TestServerInitializer());

            // bind端口号
            ChannelFuture channelFuture =   serverBootstrap.bind(8788).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 编解码合二为一
        pipeline.addLast("httpServerCodec", new HttpServerCodec());
        pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler());
    }
}
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpMessage) {
            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());

            ctx.writeAndFlush(response);
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值