




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 項目工程造價培訓課件
- 兒童多動癥的健康教育
- 部隊反邪教課件
- 高效節能電機項目經濟效益和社會效益分析報告(范文)
- 2025年會計、審計及稅務服務項目發展計劃
- 新解讀《建筑信息模型(BIM)應用標準 DBJ-T 36-069-2021》解讀
- 2025年壬基酚聚氧乙烯醚項目建議書
- 細胞生物學總結
- 2025年霍爾汽車點火系統項目合作計劃書
- 2025年花畫工藝品合作協議書
- 教師進企業實踐三方協議書
- 施工現場隱患圖片識別合集
- 山西省建設工程計價依據
- 煤礦在用安全設備檢測檢驗制度
- GB/T 24632.2-2009產品幾何技術規范(GPS)圓度第2部分:規范操作集
- GB/T 20428-2006巖石平板
- GB/T 11363-1989釬焊接頭強度試驗方法
- 內調焦準距式望遠系統光學設計2022年
- 核磁共振的發展史課件
- 切紙機安全操作規程標準范本
- 國家開放大學2022秋法理學形考1-4參考答案
評論
0/150
提交評論