




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、 Netty前言:高性能的三大主題:1) 傳輸:用什么樣的通道將數(shù)據(jù)發(fā)送給對(duì)方,BIO、NIO或者AIO,IO模型在很大程度上決定了框架的性能。2) 協(xié)議:采用什么樣的通信協(xié)議,HTTP或者內(nèi)部私有協(xié)議。協(xié)議的選擇不同,性能模型也不同。相比于公有協(xié)議,內(nèi)部私有協(xié)議的性能通??梢员辉O(shè)計(jì)的更優(yōu)。3) 線程:數(shù)據(jù)報(bào)如何讀?。孔x取之后的編解碼在哪個(gè)線程進(jìn)行,編解碼后的消息如何派發(fā),Reactor線程模型的不同,對(duì)性能的影響也非常大。Netty 高性能的表現(xiàn):1. 異步非阻塞通信2. 零拷貝1) Netty的接收和發(fā)送ByteBuffer采用DIRECT BUFFERS,使用堆外直接內(nèi)存進(jìn)行Socket
2、讀寫(xiě),不需要進(jìn)行字節(jié)緩沖區(qū)的二次拷貝2) Netty提供了組合Buffer對(duì)象,可以聚合多個(gè)ByteBuffer對(duì)象,用戶可以像操作一個(gè)Buffer那樣方便的對(duì)組合Buffer進(jìn)行操作,避免系統(tǒng)統(tǒng)通過(guò)內(nèi)存拷貝的方式將幾個(gè)小Buffer合并成一個(gè)大的Buffer。3) Netty的文件傳輸采用了transferTo方法,它可以直接將文件緩沖區(qū)的數(shù)據(jù)發(fā)送到目標(biāo)Channel,避免了傳統(tǒng)通過(guò)循環(huán)write方式導(dǎo)致的內(nèi)存拷貝問(wèn)題。3. 內(nèi)存池4. 高效的Reactor線程模型5. 無(wú)鎖化的串行設(shè)計(jì)理念6. 高效的并發(fā)編程7. 高性能的序列化框架8. 靈活的TCP參數(shù)配置能力Netty 服務(wù)端創(chuàng)建(詳細(xì)
3、解析):1. 創(chuàng)建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服務(wù)端 * * author zhouxm * */public
5、 class TimeService public void bind(int port) throws Exception / 配置NIO服務(wù)端線程組EventLoopGroup bossGroup = new NioEventLoopGroup();/ 用于服務(wù)端接收客戶端的鏈接EventLoopGroup workGroup = new NioEventLoopGroup();/ 用于SocketChannel網(wǎng)絡(luò)讀寫(xiě)try / 創(chuàng)建NIO服務(wù)端輔助啟動(dòng)類(lèi)ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workGr
6、oup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHander();/ 綁定監(jiān)聽(tīng)端口,同步等待成功ChannelFuture f = b.bind(port).sync();/ 等待監(jiān)聽(tīng)端口關(guān)閉f.channel().closeFuture().sync();/ b.bind(port).sync().channel().closeFuture().sync();/也可以這樣將上面兩步驟合并,使代碼更簡(jiǎn)潔 finally /
7、 退出,釋放線程池資源bossGroup.shutdownGracefully();workGroup.shutdownGracefully();/ 用戶處理網(wǎng)絡(luò)IO事件,類(lèi)似于Reactor模式中的handle類(lèi) 例:消息編解碼 日志打印private class ChildChannelHander extends ChannelInitializer<SocketChannel> Overrideprotected void initChannel(SocketChannel arg0) throws Exception / TODO Auto-generated metho
8、d stubChannelPipeline pipeline = arg0.pipeline();/ 以("n")為結(jié)尾分割的 解碼器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類(lèi) * * 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轉(zhuǎn)換成Netty ByteBuf 類(lèi)似于jdk中的ByteBufferbyte req = new bytebuf.readableBytes();/ 根據(jù)字節(jié)數(shù)創(chuàng)建byte數(shù)組buf.readBytes(req);/ 將緩沖區(qū)中的字節(jié)數(shù)組復(fù)制到 byte數(shù)組中String body = new String(re
13、q, "utf-8");/ 創(chuàng)建構(gòu)造函數(shù)接收消息System.out.print("client send message :" + body);/ 打印String resString = "response msg to client "ByteBuf b = Unpooled.copiedBuffer(resString.getBytes();ctx.write(b);/ 發(fā)送消息給客戶端/* * (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();/ 將隊(duì)列中的消息寫(xiě)入到SocketChannel發(fā)送給客戶端/* * (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();/ 關(guān)閉,釋放資源創(chuàng)建Netty客戶端:一創(chuàng)建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 / 創(chuàng)建NIO客戶端輔助啟動(dòng)
18、類(lèi)Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ClientTimeHander();/發(fā)起異步鏈接操作ChannelFuture f = b.connect(host, port).sync();/等待客戶端鏈路關(guān)閉f.channel().closeFuture().sync(); finally group.shutdownGracefully();/ 關(guān)閉 釋放資源private
19、 class ClientTimeHander extends ChannelInitializer<SocketChannel> Overrideprotected void initChannel(SocketChannel arg0) throws Exception / TODO Auto-generated method stubChannelPipeline pipeline = arg0.pipeline();/ 以("n")為結(jié)尾分割的 解碼器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();二創(chuàng)建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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 測(cè)繪工程中特殊地形測(cè)量對(duì)策與優(yōu)化方案
- 民政系統(tǒng)檔案管理辦法
- 征用法律客體范圍界定研究
- 醫(yī)藥耗材流通管理辦法
- 學(xué)校安全教育課程:設(shè)計(jì)與實(shí)施
- 高校校園交通安全管理模式創(chuàng)新研究
- 材料采購(gòu)預(yù)算管理辦法
- 體育從業(yè)機(jī)構(gòu)管理辦法
- 教科書(shū)內(nèi)容組織與科學(xué)設(shè)計(jì)
- 在線開(kāi)放課程建設(shè)與管理策略
- 監(jiān)理通知回執(zhí)單新
- 母嬰保健-助產(chǎn)技術(shù)理論考核試題題庫(kù)及答案
- 保潔服務(wù)考核表(僅供參考)
- dd5e人物卡可填充格式角色卡夜版
- 教師進(jìn)企業(yè)實(shí)踐三方協(xié)議書(shū)
- 施工現(xiàn)場(chǎng)隱患圖片識(shí)別合集
- 山西省建設(shè)工程計(jì)價(jià)依據(jù)
- 煤礦在用安全設(shè)備檢測(cè)檢驗(yàn)制度
- GB/T 24632.2-2009產(chǎn)品幾何技術(shù)規(guī)范(GPS)圓度第2部分:規(guī)范操作集
- GB/T 20428-2006巖石平板
- GB/T 11363-1989釬焊接頭強(qiáng)度試驗(yàn)方法
評(píng)論
0/150
提交評(píng)論