




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、 Netty前言:高性能的三大主題:1) 傳輸:用什么樣的通道將數據發送給對方,BIO、NIO或者AIO,IO模型在很大程度上決定了框架的性能。2) 協議:采用什么樣的通信協議,HTTP或者內部私有協議。協議的選擇不同,性能模型也不同。相比于公有協議,內部私有協議的性能通常可以被設計的更優。3) 線程:數據報如何讀取?讀取之后的編解碼在哪個線程進行,編解碼后的消息如何派發,Reactor線程模型的不同,對性能的影響也非常大。Netty 高性能的表現:1. 異步非阻塞通信2. 零拷貝1) Netty的接收和發送ByteBuffer采用DIRECT BUFFERS,使用堆外直接內存進行Socket
2、讀寫,不需要進行字節緩沖區的二次拷貝2) Netty提供了組合Buffer對象,可以聚合多個ByteBuffer對象,用戶可以像操作一個Buffer那樣方便的對組合Buffer進行操作,避免系統統通過內存拷貝的方式將幾個小Buffer合并成一個大的Buffer。3) Netty的文件傳輸采用了transferTo方法,它可以直接將文件緩沖區的數據發送到目標Channel,避免了傳統通過循環write方式導致的內存拷貝問題。3. 內存池4. 高效的Reactor線程模型5. 無鎖化的串行設計理念6. 高效的并發編程7. 高性能的序列化框架8. 靈活的TCP參數配置能力Netty 服務端創建(詳細
3、解析):1. 創建TimeService:代碼如下:package ty.demo;import ty.bootstrap.ServerBootstrap;import ty.channel.ChannelFuture;import ty.channel.ChannelInitializer;import ty.channel.ChannelOption;import ty.channel.ChannelPipeline;import ty.channel.EventLoopGroup;import ty.channel.nio.NioEventLoopGroup;import ty.chan
4、nel.socket.SocketChannel;import ty.channel.socket.nio.NioServerSocketChannel;import ty.handler.codec.DelimiterBasedFrameDecoder;import ty.handler.codec.Delimiters;import ty.handler.codec.string.StringDecoder;import ty.handler.codec.string.StringEncoder;/* * Time Netty服務端 * * author zhouxm * */public
5、 class TimeService public void bind(int port) throws Exception / 配置NIO服務端線程組EventLoopGroup bossGroup = new NioEventLoopGroup();/ 用于服務端接收客戶端的鏈接EventLoopGroup workGroup = new NioEventLoopGroup();/ 用于SocketChannel網絡讀寫try / 創建NIO服務端輔助啟動類ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workGr
6、oup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHander();/ 綁定監聽端口,同步等待成功ChannelFuture f = b.bind(port).sync();/ 等待監聽端口關閉f.channel().closeFuture().sync();/ b.bind(port).sync().channel().closeFuture().sync();/也可以這樣將上面兩步驟合并,使代碼更簡潔 finally /
7、 退出,釋放線程池資源bossGroup.shutdownGracefully();workGroup.shutdownGracefully();/ 用戶處理網絡IO事件,類似于Reactor模式中的handle類 例:消息編解碼 日志打印private class ChildChannelHander extends ChannelInitializer<SocketChannel> Overrideprotected void initChannel(SocketChannel arg0) throws Exception / TODO Auto-generated metho
8、d stubChannelPipeline pipeline = arg0.pipeline();/ 以("n")為結尾分割的 解碼器pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,Delimiters.lineDelimiter();/ 字符串解碼 和 編碼pipeline.addLast("decoder", new StringDecoder();pipeline.addLast("encoder", new StringEncod
9、er();/ 自己的邏輯Handlerpipeline.addLast("handler", new TimeServerHander();public static void main(String args)int port = 8080;try new TimeService().bind(port); catch (Exception e) / TODO Auto-generated catch blocke.printStackTrace();2. TimeServerHander:代碼如下:package ty.demo;import ty.buffer.Byt
10、eBuf;import ty.buffer.Unpooled;import ty.channel.ChannelHandlerAdapter;import ty.channel.ChannelHandlerContext;/* * 邏輯handle類 * * author zhouxm * */public class TimeServerHander extends ChannelHandlerAdapter /* * (non-Javadoc) * * see * ty.channel.ChannelHandlerAdapter#channelActive(ty.channel * .Ch
11、annelHandlerContext) */Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception / TODO Auto-generated method stubsuper.channelActive(ctx);/* * (non-Javadoc) * * see ty.channel.ChannelHandlerAdapter#channelRead(ty.channel. * ChannelHandlerContext, java.lang.Object) */Overridepubl
12、ic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception / TODO Auto-generated method stubByteBuf buf = (ByteBuf) msg;/ 將msg轉換成Netty ByteBuf 類似于jdk中的ByteBufferbyte req = new bytebuf.readableBytes();/ 根據字節數創建byte數組buf.readBytes(req);/ 將緩沖區中的字節數組復制到 byte數組中String body = new String(re
13、q, "utf-8");/ 創建構造函數接收消息System.out.print("client send message :" + body);/ 打印String resString = "response msg to client "ByteBuf b = Unpooled.copiedBuffer(resString.getBytes();ctx.write(b);/ 發送消息給客戶端/* * (non-Javadoc) * * see * ty.channel.ChannelHandlerAdapter#channelRe
14、adComplete(ty.channel * .ChannelHandlerContext) */Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception / TODO Auto-generated method stubctx.flush();/ 將隊列中的消息寫入到SocketChannel發送給客戶端/* * (non-Javadoc) * * see * ty.channel.ChannelHandlerAdapter#exceptionCaught(ty.channel *
15、 .ChannelHandlerContext, java.lang.Throwable) */Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception / TODO Auto-generated method stubctx.close();/ 關閉,釋放資源創建Netty客戶端:一創建TimeClient:package ty.demo;import ty.bootstrap.Bootstrap;import ty.channel.ChannelFuture
16、;import ty.channel.ChannelInitializer;import ty.channel.ChannelOption;import ty.channel.ChannelPipeline;import ty.channel.EventLoopGroup;import ty.channel.nio.NioEventLoopGroup;import ty.channel.socket.SocketChannel;import ty.channel.socket.nio.NioSocketChannel;import ty.handler.codec.DelimiterBased
17、FrameDecoder;import ty.handler.codec.Delimiters;import ty.handler.codec.string.StringDecoder;import ty.handler.codec.string.StringEncoder;public class TimeClient public void connect(String host, int port) throws Exception / 配置客戶端NIO線程組EventLoopGroup group = new NioEventLoopGroup();try / 創建NIO客戶端輔助啟動
18、類Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ClientTimeHander();/發起異步鏈接操作ChannelFuture f = b.connect(host, port).sync();/等待客戶端鏈路關閉f.channel().closeFuture().sync(); finally group.shutdownGracefully();/ 關閉 釋放資源private
19、 class ClientTimeHander extends ChannelInitializer<SocketChannel> Overrideprotected void initChannel(SocketChannel arg0) throws Exception / TODO Auto-generated method stubChannelPipeline pipeline = arg0.pipeline();/ 以("n")為結尾分割的 解碼器pipeline.addLast("framer", new DelimiterBa
20、sedFrameDecoder(8192,Delimiters.lineDelimiter();/ 字符串解碼 和 編碼pipeline.addLast("decoder", new StringDecoder();pipeline.addLast("encoder", new StringEncoder();/ 自己的邏輯Handlerpipeline.addLast("handler", new TimeClientHander();public static void main(String args) / TODO Auto-
21、generated method stubString host = "localhost"int port = 8080;try new TimeClient().connect(host, port); catch (Exception e) / TODO Auto-generated catch blocke.printStackTrace();二創建TimeClientHander:package ty.demo;import ty.buffer.ByteBuf;import ty.buffer.Unpooled;import ty.channel.ChannelH
22、andlerAdapter;import ty.channel.ChannelHandlerContext;public class TimeClientHander extends ChannelHandlerAdapter private final ByteBuf firstMsg;public TimeClientHander()byte req = "send msg to server date".getBytes();firstMsg = Unpooled.buffer(req.length);firstMsg.writeBytes(req);/* (non-Javadoc) * see ty.channel.ChannelHandlerAdapter#channelActive(ty.channel.ChannelHandlerContext) */Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception / TODO Auto-generated method stubctx.writeAndFlush(firstMsg);/* (non-Javadoc) * see ty.channel.Chan
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 客戶經理年終個人工作總結模版
- 社區護理資源配置優化策略
- 快速充電技術的探索
- 風險管理套期保值講解
- 火電廠生產工藝流程
- 養老護理標準化流程
- 余姚四中教師考試試題及答案
- 有關古代法律的考試題及答案
- 銀行行長面試題目及答案
- 老人晨起護理
- 托育機構消防安全培訓
- 《現代庫存管理:模型、算法與Python實現》 課件全套 楊超林 第1-17章 現代庫存管理概述-某家電企業H的制造網絡庫存優化實戰
- (正式版)QBT 5998-2024 寵物尿墊(褲)
- (正式版)HGT 6276-2024 雙酚F型環氧樹脂
- 補習班輔導班學員合同協議書范本
- 操作系統智慧樹知到期末考試答案2024年
- 離婚案件中夫妻房產分割問題研究
- APQP全套表格范例
- 《馬說》復習課件
- 【可行性報告】2023年房屋租賃行業項目可行性分析報告
- 大規模模型蒸餾技術
評論
0/150
提交評論