SlideShare uma empresa Scribd logo
1 de 32
Baixar para ler offline
深入浅出Netty
 雷腾 L.T - leiteng@taobao.com
搜索算法不技术 – 搜索应用团队
Netty是什么?
            Netty 提供异步的、事件驱动的
            网络应用程序框架和工具,用
            以快速开发高性能、高可靠性
             的网络服务器和客户端程序
Netty的架构
Netty的特性

    Netty 有些什
    么特性呢?
Netty的特性
 设计
 –   统一的API,适用于丌同的协议(阻塞和非阻塞)
 –   基于灵活、可扩展的事件驱动模型
 –   高度可定制的线程模型
 –   可靠的无连接数据Socket支持(UDP)
 性能
 – 更好的吞吐量,低延迟
 – 更省资源
 – 尽量减少丌必要的内存拷贝
Netty的特性
 安全
 – 完整的SSL/ TLS和STARTTLS的支持
 – 能在Applet不谷歌Android的限制环境运行良好
 健壮性
 – 丌再因过快、过慢或超负载连接导致
   OutOfMemoryError
 – 丌再有在高速网络环境下NIO读写频率丌一致的问题
 易用
 – 完善的Java doc,用户指南和样例
 – 简洁简单
 – 仅依赖于JDK1.5
深入浅出Netty


  But how to use it?
Hello World in Netty
 HelloWorldServer
  ServerBootstrap bootstrap = new ServerBootstrap(new
    NioServerSocketChannelFactory(
    Executors.newCachedThreadPool(),
    Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
      public ChannelPipeline getPipeline() {
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("handler", new HelloWorldServerHandler());
        return pipeline;
      }
  });

  bootstrap.bind(new InetSocketAddress(8080));
Hello World in Netty
 HelloWorldServerHandler
  public void channelConnected(ChannelHandlerContext ctx,
    ChannelStateEvent e) throws Exception {
    e.getChannel().write("Hello, World");
  }

  public void exceptionCaught(ChannelHandlerContext ctx,
    ExceptionEvent e) {
    logger.log(Level.WARNING, "Unexpected exception from
    downstream.", e.getCause());
    e.getChannel().close();
  }
Hello World in Netty
 HelloWorldClient
  ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
  Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

  bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
     public ChannelPipeline getPipeline() {
            ChannelPipeline pipeline = pipeline();
            pipeline.addLast("decoder", new StringDecoder());
            pipeline.addLast("encoder", new StringEncoder());
            pipeline.addLast("handler", new HelloWorldClientHandler());
            return pipeline;
        }
  });

  ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));

  future.getChannel().getCloseFuture().awaitUninterruptibly();

  bootstrap.releaseExternalResources();
Hello World in Netty
 HelloWorldClientHandler
  public void messageReceived(ChannelHandlerContext ctx,
    MessageEvent e) {
      String message = (String) e.getMessage();
      System.out.println(message);
      e.getChannel().close();
  }
  public void exceptionCaught(ChannelHandlerContext ctx,
    ExceptionEvent e) {
      logger.log(Level.WARNING, "Unexpected exception from
        downstream.", e.getCause());
      e.getChannel().close();
  }
深入浅出Netty

  刨根问底的勇气?
Netty源码分析
 org.jboss.netty.bootstrap
    Bootstrap : ChannelFactory , ChannelPipeline , ChannelPipelineFactory
         初始化channel的辅助类
         为具体的子类提供公共数据结构
    ServerBootstrap: bind()
         创建服务器端channel的辅助类
         接收connection请求
    ClientBootstrap : connect()
         创建客户端channel的辅助类
         发起connection请求
    ConnectionlessBootstrap : connect() , bind()
         创建无连接传输channel的辅助类(UDP)
         包括Client 和Server
Netty源码分析
 org.jboss.netty.buffer
 取代nio 中的java.nio.ByteBuffer,相比ByteBuffer
    可以根据需要自定义buffer type
    内置混合的buffer type, 以实现zero-copy
    提供类似StringBuffer的动态dynamic buffer
    丌需要调用flip方法
    更快的性能
 推荐使用ChannelBuffers的静态工厂创建ChannelBuffer
Netty源码分析
 org.jboss.netty.channel
  channel核心api,包括异步和事件驱动等各种传送接口
 org.jboss.netty.channel.group
  channel group,帮助用户维护channel列表
 org.jboss.netty.channel.local
  一种虚拟传输方式,允许同一个虚拟机上的两个部分可以互相通信
 org.jboss.netty.channel.socket
  TCP, UDP接口,继承了核心的channel API
 org.jboss.netty.channel.socket.nio
  基于nio的Socket channel实现
 org.jboss.netty.channel.socket.oio
  基于老io的Socket channel实现
 org.jboss.netty.channel.socket.http
  基于http的客户端和相应的server端的实现,工作在有防火墙的情况
Netty源码分析
 org.jboss.netty.container
 各种容器的兼容
 org.jboss.netty.container.microcontainer
 JBoss Microcontainer 集成接口
 org.jboss.netty.container.osgi
 OSGi framework集成接口
 org.jboss.netty.container.spring
 Spring framework集成接口
Netty源码分析
 org.jboss.netty.handler
 处理器
 org.jboss.netty.handler.codec
 编码解码器
 org.jboss.netty.handler.execution
 基于Executor的实现
 org.jboss.netty.handler.queue
 将event存入内部队列的处理
 org.jboss.netty.handler.ssl
 基于SSLEngine的SSL以及TLS实现
 org.jboss.netty.handler.stream
 异步写入大数据,丌会产生outOfMemory 也丌会花费很多内存
 org.jboss.netty.handler.timeout
 通过Timer来对读写超时或者闲置链接进行通知
Netty源码分析
org.jboss.netty.handler.codec.base64 Base64 编码
org.jboss.netty.handler.codec.compression 压缩格式
org.jboss.netty.handler.codec.embedder 嵌入模式下编码和解码
org.jboss.netty.handler.codec.frame 评估流的数据的排列和内容
org.jboss.netty.handler.codec.http.websocket websocket编码解码
org.jboss.netty.handler.codec.http http的编码解码以及类型信息
org.jboss.netty.handler.codec.oneone 对象到对象编码解码
org.jboss.netty.handler.codec.protobuf Protocol Buffers的编码解码
org.jboss.netty.handler.codec.replay 在阻塞io中实现非阻塞解码
org.jboss.netty.handler.codec.rtsp RTSP的编码解码
org.jboss.netty.handler.codec.serialization 序列化对象到bytebuffer实现
org.jboss.netty.handler.codec.string 字符串编码解码,继承oneone
Netty源码分析
 org.jboss.netty.logging
 根据丌同的log framework 实现的类
 org.jboss.netty.util
 netty util类
 org.jboss.netty.util.internal
 netty内部util类,丌被外部使用
Netty事件驱动模型
Netty事件驱动模型
Netty Pipeline 流处理
 Upstream 接收请求
 Downstream 发送请求
  ChannelPipeline p = Channels.pipeline();
  p.addLast("1", new UpstreamHandlerA());
  p.addLast("2", new UpstreamHandlerB());
  p.addLast("3", new DownstreamHandlerA());
  p.addLast("4", new DownstreamHandlerB());
  p.addLast("5", new UpstreamHandlerX());

  Upstream: 1  2  5 顺序处理
  Downstream: 4  3 逆序处理
Netty 通用通信API
 connect
 bind
 write
 close
 disconnect
 unbind
 isOpen
 isBound
 isConnected
 isReadable
 isWrita ble
Netty Zero-Copy-Capable Buffer
  序列访问索引
+-------------------+------------------+------------------+
| discardable bytes | readable bytes | writable bytes |
+-------------------+------------------+------------------+
|                   |                  |                  |
 0 <= readerIndex <= writerIndex <= capacity

  get & set : not modify the readerIndex or writerIndex
  read & write : modify the readerIndex or writerIndex
Netty Zero-Copy-Capable Buffer
 ChannelBuffer
  – 定义接口
 ChannelBuffers
  – 静态工厂
  – 隐藏具体类型
Netty数据流分析
 服务器启动

 服务器主通道监听

 服务器子通道开通

 客户端启动

 客户端主通道监听

 客户端子通道开通
Netty VS Mina
Mina 架构
Mina 服务器端架构
IO Acceptor
 – 实现了IoService
 – 监听网络请求或数据包
 – 新连接,创建session
IO Filter
 – 过滤和传输
 – 编码解码
IO Handler
 – 实现业务逻辑
Mina 客户架构
 IO Connector
 –   实现IO Server
 –   连接到Socket
 –   bind到Server
 –   创建session
 IO Filter
 – 过滤和传输
 – 编码解码
 IO Handler
 – 实现业务逻辑
Netty VS Mina
 Netty基于Pipeline处理,Mina基于Filter过滤
 Netty的事件驱动模型具有更好的扩展性和易用性
 Https,SSL,PB,RSTP,Text &Binary等协议支持
 Netty中UDP传输有更好的支持
 官方测试Netty比Mina性能更好
Q&A
         雷腾 L.T
Email:leiteng@taobao.com

Mais conteúdo relacionado

Mais procurados

lua & ngx_lua 的介绍与应用
lua & ngx_lua 的介绍与应用lua & ngx_lua 的介绍与应用
lua & ngx_lua 的介绍与应用hugo
 
Improvements Made in KoP 2.9.0 - Pulsar Summit Asia 2021
Improvements Made in KoP 2.9.0  - Pulsar Summit Asia 2021Improvements Made in KoP 2.9.0  - Pulsar Summit Asia 2021
Improvements Made in KoP 2.9.0 - Pulsar Summit Asia 2021StreamNative
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceHo Kim
 
Monitor is all for ops
Monitor is all for opsMonitor is all for ops
Monitor is all for ops琛琳 饶
 
Openstack neutron 原理详解
Openstack neutron 原理详解Openstack neutron 原理详解
Openstack neutron 原理详解Yong Luo
 
再生龍於雲端環境之應用
再生龍於雲端環境之應用再生龍於雲端環境之應用
再生龍於雲端環境之應用Chenkai Sun
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战rfyiamcool
 
千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7Justin Lin
 
Using armeria to write your RPC
Using armeria to write your RPCUsing armeria to write your RPC
Using armeria to write your RPCkoji lin
 
Software Engineer Talk
Software Engineer TalkSoftware Engineer Talk
Software Engineer TalkLarry Cai
 
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)Jian-Kai Wang
 
Golangintro
GolangintroGolangintro
Golangintro理 傅
 
OpenResty 项目模块化最佳实践
OpenResty 项目模块化最佳实践OpenResty 项目模块化最佳实践
OpenResty 项目模块化最佳实践Orangle Liu
 
Linux performance analysis cpu
Linux performance analysis cpuLinux performance analysis cpu
Linux performance analysis cpu静 丁
 
Rpc原理与实现
Rpc原理与实现Rpc原理与实现
Rpc原理与实现wavefly
 
20081128 http caching_in_php
20081128 http caching_in_php20081128 http caching_in_php
20081128 http caching_in_phpHunter Wu
 
DNS协议与应用简介
DNS协议与应用简介DNS协议与应用简介
DNS协议与应用简介琛琳 饶
 
Network and Multitasking
Network and MultitaskingNetwork and Multitasking
Network and Multitaskingyarshure Kong
 
聊聊我接触的集群管理
聊聊我接触的集群管理聊聊我接触的集群管理
聊聊我接触的集群管理rfyiamcool
 

Mais procurados (20)

lua & ngx_lua 的介绍与应用
lua & ngx_lua 的介绍与应用lua & ngx_lua 的介绍与应用
lua & ngx_lua 的介绍与应用
 
Improvements Made in KoP 2.9.0 - Pulsar Summit Asia 2021
Improvements Made in KoP 2.9.0  - Pulsar Summit Asia 2021Improvements Made in KoP 2.9.0  - Pulsar Summit Asia 2021
Improvements Made in KoP 2.9.0 - Pulsar Summit Asia 2021
 
OpenResty/Lua Practical Experience
OpenResty/Lua Practical ExperienceOpenResty/Lua Practical Experience
OpenResty/Lua Practical Experience
 
Nio trick and trap
Nio trick and trapNio trick and trap
Nio trick and trap
 
Monitor is all for ops
Monitor is all for opsMonitor is all for ops
Monitor is all for ops
 
Openstack neutron 原理详解
Openstack neutron 原理详解Openstack neutron 原理详解
Openstack neutron 原理详解
 
再生龍於雲端環境之應用
再生龍於雲端環境之應用再生龍於雲端環境之應用
再生龍於雲端環境之應用
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战
 
千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7千呼萬喚始出來的 Java SE 7
千呼萬喚始出來的 Java SE 7
 
Using armeria to write your RPC
Using armeria to write your RPCUsing armeria to write your RPC
Using armeria to write your RPC
 
Software Engineer Talk
Software Engineer TalkSoftware Engineer Talk
Software Engineer Talk
 
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
CKAN : 資料開放平台技術介紹 (CAKN : Technical Introduction to Open Data Portal)
 
Golangintro
GolangintroGolangintro
Golangintro
 
OpenResty 项目模块化最佳实践
OpenResty 项目模块化最佳实践OpenResty 项目模块化最佳实践
OpenResty 项目模块化最佳实践
 
Linux performance analysis cpu
Linux performance analysis cpuLinux performance analysis cpu
Linux performance analysis cpu
 
Rpc原理与实现
Rpc原理与实现Rpc原理与实现
Rpc原理与实现
 
20081128 http caching_in_php
20081128 http caching_in_php20081128 http caching_in_php
20081128 http caching_in_php
 
DNS协议与应用简介
DNS协议与应用简介DNS协议与应用简介
DNS协议与应用简介
 
Network and Multitasking
Network and MultitaskingNetwork and Multitasking
Network and Multitasking
 
聊聊我接触的集群管理
聊聊我接触的集群管理聊聊我接触的集群管理
聊聊我接触的集群管理
 

Destaque

Zero-Copy Event-Driven Servers with Netty
Zero-Copy Event-Driven Servers with NettyZero-Copy Event-Driven Servers with Netty
Zero-Copy Event-Driven Servers with NettyDaniel Bimschas
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System DevelopmentAllan Huang
 
Netty Notes Part 3 - Channel Pipeline and EventLoops
Netty Notes Part 3 - Channel Pipeline and EventLoopsNetty Notes Part 3 - Channel Pipeline and EventLoops
Netty Notes Part 3 - Channel Pipeline and EventLoopsRick Hightower
 
Netty - a pragmatic introduction
Netty - a pragmatic introductionNetty - a pragmatic introduction
Netty - a pragmatic introductionRaphael Stary
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transferVictor Cherkassky
 
Netty from the trenches
Netty from the trenchesNetty from the trenches
Netty from the trenchesJordi Gerona
 
Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Jaap ter Woerds
 
Nettyらへん
NettyらへんNettyらへん
NettyらへんGo Tanaka
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyErsin Er
 
Real time analytics with Netty, Storm, Kafka
Real time analytics with Netty, Storm, KafkaReal time analytics with Netty, Storm, Kafka
Real time analytics with Netty, Storm, KafkaTrieu Nguyen
 
Xitrum internals
Xitrum internalsXitrum internals
Xitrum internalsNgoc Dao
 
Experience with Kafka & Storm
Experience with Kafka & StormExperience with Kafka & Storm
Experience with Kafka & StormOtto Mok
 
WebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST MicroserviceWebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST MicroserviceRick Hightower
 
Subversion on-the-fly replication
Subversion on-the-fly replicationSubversion on-the-fly replication
Subversion on-the-fly replicationnormanmaurer
 
Netty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersNetty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersRick Hightower
 

Destaque (20)

Zero-Copy Event-Driven Servers with Netty
Zero-Copy Event-Driven Servers with NettyZero-Copy Event-Driven Servers with Netty
Zero-Copy Event-Driven Servers with Netty
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Netty 4-based RPC System Development
Netty 4-based RPC System DevelopmentNetty 4-based RPC System Development
Netty 4-based RPC System Development
 
Netty Notes Part 3 - Channel Pipeline and EventLoops
Netty Notes Part 3 - Channel Pipeline and EventLoopsNetty Notes Part 3 - Channel Pipeline and EventLoops
Netty Notes Part 3 - Channel Pipeline and EventLoops
 
Netty - a pragmatic introduction
Netty - a pragmatic introductionNetty - a pragmatic introduction
Netty - a pragmatic introduction
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
Notes on Netty baics
Notes on Netty baicsNotes on Netty baics
Notes on Netty baics
 
Netty from the trenches
Netty from the trenchesNetty from the trenches
Netty from the trenches
 
Building Netty Servers
Building Netty ServersBuilding Netty Servers
Building Netty Servers
 
Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...Building scalable network applications with Netty (as presented on NLJUG JFal...
Building scalable network applications with Netty (as presented on NLJUG JFal...
 
Netty
NettyNetty
Netty
 
Nettyらへん
NettyらへんNettyらへん
Nettyらへん
 
Asynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with NettyAsynchronous, Event-driven Network Application Development with Netty
Asynchronous, Event-driven Network Application Development with Netty
 
Real time analytics with Netty, Storm, Kafka
Real time analytics with Netty, Storm, KafkaReal time analytics with Netty, Storm, Kafka
Real time analytics with Netty, Storm, Kafka
 
Xitrum internals
Xitrum internalsXitrum internals
Xitrum internals
 
Experience with Kafka & Storm
Experience with Kafka & StormExperience with Kafka & Storm
Experience with Kafka & Storm
 
WebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST MicroserviceWebSocket MicroService vs. REST Microservice
WebSocket MicroService vs. REST Microservice
 
Netty4
Netty4Netty4
Netty4
 
Subversion on-the-fly replication
Subversion on-the-fly replicationSubversion on-the-fly replication
Subversion on-the-fly replication
 
Netty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and BuffersNetty Notes Part 2 - Transports and Buffers
Netty Notes Part 2 - Transports and Buffers
 

Semelhante a 深入浅出Netty l.t

高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕ideawu
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geekJohnson Gau
 
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUGYingSiang Geng
 
构建ActionScript游戏服务器,支持超过15000并发连接
构建ActionScript游戏服务器,支持超过15000并发连接 构建ActionScript游戏服务器,支持超过15000并发连接
构建ActionScript游戏服务器,支持超过15000并发连接 Renaun Erickson
 
部門會議 950619 Leon的錦囊妙計
部門會議 950619 Leon的錦囊妙計部門會議 950619 Leon的錦囊妙計
部門會議 950619 Leon的錦囊妙計Leon Chuang
 
Static server介绍
Static server介绍Static server介绍
Static server介绍sun jamie
 
高性能远程调用解决方案
高性能远程调用解决方案高性能远程调用解决方案
高性能远程调用解决方案Ady Liu
 
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509tidesq
 
ASP.NET Core 2.1設計新思維與新發展
ASP.NET  Core 2.1設計新思維與新發展ASP.NET  Core 2.1設計新思維與新發展
ASP.NET Core 2.1設計新思維與新發展江華 奚
 
Huangjing renren
Huangjing renrenHuangjing renren
Huangjing renrend0nn9n
 
Python 于 webgame 的应用
Python 于 webgame 的应用Python 于 webgame 的应用
Python 于 webgame 的应用勇浩 赖
 
廖雪峰 Saa s ovp
廖雪峰 Saa s ovp廖雪峰 Saa s ovp
廖雪峰 Saa s ovpdrewz lin
 
IoTDB Quick Start
IoTDB Quick StartIoTDB Quick Start
IoTDB Quick StartJialinQiao
 
Pm 04 华胜天成openstack实践汇报-20120808
Pm 04 华胜天成openstack实践汇报-20120808Pm 04 华胜天成openstack实践汇报-20120808
Pm 04 华胜天成openstack实践汇报-20120808OpenCity Community
 
走马观花— Haskell Web 开发
走马观花— Haskell Web 开发走马观花— Haskell Web 开发
走马观花— Haskell Web 开发Gump Law
 
PHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB ServerPHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB Server志賢 黃
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式Shengyou Fan
 
用Cython封装c++代码为python模块的一点经验
用Cython封装c++代码为python模块的一点经验用Cython封装c++代码为python模块的一点经验
用Cython封装c++代码为python模块的一点经验Leo Zhou
 
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC
 

Semelhante a 深入浅出Netty l.t (20)

高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕高性能并发Web服务器实现核心内幕
高性能并发Web服务器实现核心内幕
 
利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek利用Signalr打造即時通訊@Tech day geek
利用Signalr打造即時通訊@Tech day geek
 
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
探索 ISTIO 新型 DATA PLANE 架構 AMBIENT MESH - GOLANG TAIWAN GATHERING #77 X CNTUG
 
构建ActionScript游戏服务器,支持超过15000并发连接
构建ActionScript游戏服务器,支持超过15000并发连接 构建ActionScript游戏服务器,支持超过15000并发连接
构建ActionScript游戏服务器,支持超过15000并发连接
 
部門會議 950619 Leon的錦囊妙計
部門會議 950619 Leon的錦囊妙計部門會議 950619 Leon的錦囊妙計
部門會議 950619 Leon的錦囊妙計
 
Osgi Intro
Osgi IntroOsgi Intro
Osgi Intro
 
Static server介绍
Static server介绍Static server介绍
Static server介绍
 
高性能远程调用解决方案
高性能远程调用解决方案高性能远程调用解决方案
高性能远程调用解决方案
 
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
Linux c++ 编程之链接与装载 -基础篇--v0.3--20120509
 
ASP.NET Core 2.1設計新思維與新發展
ASP.NET  Core 2.1設計新思維與新發展ASP.NET  Core 2.1設計新思維與新發展
ASP.NET Core 2.1設計新思維與新發展
 
Huangjing renren
Huangjing renrenHuangjing renren
Huangjing renren
 
Python 于 webgame 的应用
Python 于 webgame 的应用Python 于 webgame 的应用
Python 于 webgame 的应用
 
廖雪峰 Saa s ovp
廖雪峰 Saa s ovp廖雪峰 Saa s ovp
廖雪峰 Saa s ovp
 
IoTDB Quick Start
IoTDB Quick StartIoTDB Quick Start
IoTDB Quick Start
 
Pm 04 华胜天成openstack实践汇报-20120808
Pm 04 华胜天成openstack实践汇报-20120808Pm 04 华胜天成openstack实践汇报-20120808
Pm 04 华胜天成openstack实践汇报-20120808
 
走马观花— Haskell Web 开发
走马观花— Haskell Web 开发走马观花— Haskell Web 开发
走马观花— Haskell Web 开发
 
PHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB ServerPHP 應用之一 socket funion : 偽 WEB Server
PHP 應用之一 socket funion : 偽 WEB Server
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
 
用Cython封装c++代码为python模块的一点经验
用Cython封装c++代码为python模块的一点经验用Cython封装c++代码为python模块的一点经验
用Cython封装c++代码为python模块的一点经验
 
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning ServicestwMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
twMVC#46_SQL Server 資料分析大躍進 Machine Learning Services
 

深入浅出Netty l.t

  • 1. 深入浅出Netty 雷腾 L.T - leiteng@taobao.com 搜索算法不技术 – 搜索应用团队
  • 2. Netty是什么? Netty 提供异步的、事件驱动的 网络应用程序框架和工具,用 以快速开发高性能、高可靠性 的网络服务器和客户端程序
  • 4. Netty的特性 Netty 有些什 么特性呢?
  • 5. Netty的特性 设计 – 统一的API,适用于丌同的协议(阻塞和非阻塞) – 基于灵活、可扩展的事件驱动模型 – 高度可定制的线程模型 – 可靠的无连接数据Socket支持(UDP) 性能 – 更好的吞吐量,低延迟 – 更省资源 – 尽量减少丌必要的内存拷贝
  • 6. Netty的特性 安全 – 完整的SSL/ TLS和STARTTLS的支持 – 能在Applet不谷歌Android的限制环境运行良好 健壮性 – 丌再因过快、过慢或超负载连接导致 OutOfMemoryError – 丌再有在高速网络环境下NIO读写频率丌一致的问题 易用 – 完善的Java doc,用户指南和样例 – 简洁简单 – 仅依赖于JDK1.5
  • 7. 深入浅出Netty But how to use it?
  • 8. Hello World in Netty HelloWorldServer ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new HelloWorldServerHandler()); return pipeline; } }); bootstrap.bind(new InetSocketAddress(8080));
  • 9. Hello World in Netty HelloWorldServerHandler public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { e.getChannel().write("Hello, World"); } public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { logger.log(Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); }
  • 10. Hello World in Netty HelloWorldClient ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); pipeline.addLast("handler", new HelloWorldClientHandler()); return pipeline; } }); ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080)); future.getChannel().getCloseFuture().awaitUninterruptibly(); bootstrap.releaseExternalResources();
  • 11. Hello World in Netty HelloWorldClientHandler public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { String message = (String) e.getMessage(); System.out.println(message); e.getChannel().close(); } public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { logger.log(Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); }
  • 13. Netty源码分析 org.jboss.netty.bootstrap Bootstrap : ChannelFactory , ChannelPipeline , ChannelPipelineFactory 初始化channel的辅助类 为具体的子类提供公共数据结构 ServerBootstrap: bind() 创建服务器端channel的辅助类 接收connection请求 ClientBootstrap : connect() 创建客户端channel的辅助类 发起connection请求 ConnectionlessBootstrap : connect() , bind() 创建无连接传输channel的辅助类(UDP) 包括Client 和Server
  • 14. Netty源码分析 org.jboss.netty.buffer 取代nio 中的java.nio.ByteBuffer,相比ByteBuffer 可以根据需要自定义buffer type 内置混合的buffer type, 以实现zero-copy 提供类似StringBuffer的动态dynamic buffer 丌需要调用flip方法 更快的性能 推荐使用ChannelBuffers的静态工厂创建ChannelBuffer
  • 15. Netty源码分析 org.jboss.netty.channel channel核心api,包括异步和事件驱动等各种传送接口 org.jboss.netty.channel.group channel group,帮助用户维护channel列表 org.jboss.netty.channel.local 一种虚拟传输方式,允许同一个虚拟机上的两个部分可以互相通信 org.jboss.netty.channel.socket TCP, UDP接口,继承了核心的channel API org.jboss.netty.channel.socket.nio 基于nio的Socket channel实现 org.jboss.netty.channel.socket.oio 基于老io的Socket channel实现 org.jboss.netty.channel.socket.http 基于http的客户端和相应的server端的实现,工作在有防火墙的情况
  • 16. Netty源码分析 org.jboss.netty.container 各种容器的兼容 org.jboss.netty.container.microcontainer JBoss Microcontainer 集成接口 org.jboss.netty.container.osgi OSGi framework集成接口 org.jboss.netty.container.spring Spring framework集成接口
  • 17. Netty源码分析 org.jboss.netty.handler 处理器 org.jboss.netty.handler.codec 编码解码器 org.jboss.netty.handler.execution 基于Executor的实现 org.jboss.netty.handler.queue 将event存入内部队列的处理 org.jboss.netty.handler.ssl 基于SSLEngine的SSL以及TLS实现 org.jboss.netty.handler.stream 异步写入大数据,丌会产生outOfMemory 也丌会花费很多内存 org.jboss.netty.handler.timeout 通过Timer来对读写超时或者闲置链接进行通知
  • 18. Netty源码分析 org.jboss.netty.handler.codec.base64 Base64 编码 org.jboss.netty.handler.codec.compression 压缩格式 org.jboss.netty.handler.codec.embedder 嵌入模式下编码和解码 org.jboss.netty.handler.codec.frame 评估流的数据的排列和内容 org.jboss.netty.handler.codec.http.websocket websocket编码解码 org.jboss.netty.handler.codec.http http的编码解码以及类型信息 org.jboss.netty.handler.codec.oneone 对象到对象编码解码 org.jboss.netty.handler.codec.protobuf Protocol Buffers的编码解码 org.jboss.netty.handler.codec.replay 在阻塞io中实现非阻塞解码 org.jboss.netty.handler.codec.rtsp RTSP的编码解码 org.jboss.netty.handler.codec.serialization 序列化对象到bytebuffer实现 org.jboss.netty.handler.codec.string 字符串编码解码,继承oneone
  • 19. Netty源码分析 org.jboss.netty.logging 根据丌同的log framework 实现的类 org.jboss.netty.util netty util类 org.jboss.netty.util.internal netty内部util类,丌被外部使用
  • 22. Netty Pipeline 流处理 Upstream 接收请求 Downstream 发送请求 ChannelPipeline p = Channels.pipeline(); p.addLast("1", new UpstreamHandlerA()); p.addLast("2", new UpstreamHandlerB()); p.addLast("3", new DownstreamHandlerA()); p.addLast("4", new DownstreamHandlerB()); p.addLast("5", new UpstreamHandlerX()); Upstream: 1  2  5 顺序处理 Downstream: 4  3 逆序处理
  • 23. Netty 通用通信API connect bind write close disconnect unbind isOpen isBound isConnected isReadable isWrita ble
  • 24. Netty Zero-Copy-Capable Buffer 序列访问索引 +-------------------+------------------+------------------+ | discardable bytes | readable bytes | writable bytes | +-------------------+------------------+------------------+ | | | | 0 <= readerIndex <= writerIndex <= capacity get & set : not modify the readerIndex or writerIndex read & write : modify the readerIndex or writerIndex
  • 25. Netty Zero-Copy-Capable Buffer ChannelBuffer – 定义接口 ChannelBuffers – 静态工厂 – 隐藏具体类型
  • 26. Netty数据流分析 服务器启动 服务器主通道监听 服务器子通道开通 客户端启动 客户端主通道监听 客户端子通道开通
  • 29. Mina 服务器端架构 IO Acceptor – 实现了IoService – 监听网络请求或数据包 – 新连接,创建session IO Filter – 过滤和传输 – 编码解码 IO Handler – 实现业务逻辑
  • 30. Mina 客户架构 IO Connector – 实现IO Server – 连接到Socket – bind到Server – 创建session IO Filter – 过滤和传输 – 编码解码 IO Handler – 实现业务逻辑
  • 31. Netty VS Mina Netty基于Pipeline处理,Mina基于Filter过滤 Netty的事件驱动模型具有更好的扩展性和易用性 Https,SSL,PB,RSTP,Text &Binary等协议支持 Netty中UDP传输有更好的支持 官方测试Netty比Mina性能更好
  • 32. Q&A 雷腾 L.T Email:leiteng@taobao.com