搭建生產級的Netty項目

来源:https://www.cnblogs.com/qupengkun/archive/2020/04/01/12614607.html
-Advertisement-
Play Games

Netty是Trustin Lee在2004年開發的一款高性能的網路應用程式框架。相比於JDK自帶的NIO,Netty做了相當多的增強,且隔離了jdk nio的實現細節,API也比較友好,還支持流量整形等高級特性。在我們常見的一些開源項目中已經普遍的應用到了Netty,比如Dubbo、Elastic ...


Netty是Trustin Lee在2004年開發的一款高性能的網路應用程式框架。相比於JDK自帶的NIO,Netty做了相當多的增強,且隔離了jdk nio的實現細節,API也比較友好,還支持流量整形等高級特性。在我們常見的一些開源項目中已經普遍的應用到了Netty,比如Dubbo、Elasticsearch、Zookeeper等。

Netty的具體開發

提示:因代碼相對較多,這裡只展示其主要部分,至於項目中用到的編解碼器、工具類,請直接拉到最後下載源碼!也歡迎順手給個Star~

需要的依賴
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-core</artifactId>
    <version>4.1.1</version>
</dependency>
<dependency>
    <groupId>io.dropwizard.metrics</groupId>
    <artifactId>metrics-jmx</artifactId>
    <version>4.1.1</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.29.Final</version>
</dependency>
Client端代碼
package com.example.nettydemo.client;

import com.example.nettydemo.client.codec.*;
import com.example.nettydemo.client.codec.dispatcher.OperationResultFuture;
import com.example.nettydemo.client.codec.dispatcher.RequestPendingCenter;
import com.example.nettydemo.client.codec.dispatcher.ResponseDispatcherHandler;
import com.example.nettydemo.common.RequestMessage;
import com.example.nettydemo.common.string.StringOperation;
import com.example.nettydemo.util.IdUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import javax.net.ssl.SSLException;
import java.util.concurrent.ExecutionException;

public class Client {

    public static void main(String[] args) throws InterruptedException, ExecutionException, SSLException {

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);

        //客戶端連接伺服器最大允許時間,預設為30s
        bootstrap.option(NioChannelOption.CONNECT_TIMEOUT_MILLIS, 30 * 1000); //10s

        NioEventLoopGroup group = new NioEventLoopGroup();
        try {

            bootstrap.group(group);

            RequestPendingCenter requestPendingCenter = new RequestPendingCenter();
            LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);

            bootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(new FrameDecoder());
                    pipeline.addLast(new FrameEncoder());

                    pipeline.addLast(new ProtocolEncoder());
                    pipeline.addLast(new ProtocolDecoder());

                    pipeline.addLast(new ResponseDispatcherHandler(requestPendingCenter));
                    pipeline.addLast(new OperationToRequestMessageEncoder());

//                    pipeline.addLast(loggingHandler);

                }
            });

            //連接服務
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8888);
            //因為future是非同步執行,所以需要先連接上後,再進行下一步操作
            channelFuture.sync();

            long streamId = IdUtil.nextId();
            /**
             * 發送數據測試,按照定義的規則組裝數據
             */
//            OrderOperation orderOperation =  new OrderOperation(1001, "你好啊,hi");
            RequestMessage requestMessage = new RequestMessage(streamId, new StringOperation(1234, "你好啊,hi"));

            //將future放入center
            OperationResultFuture operationResultFuture = new OperationResultFuture();
            requestPendingCenter.add(streamId, operationResultFuture);

            //發送消息
            for (int i = 0; i < 10; i++) {
                channelFuture.channel().writeAndFlush(requestMessage);
            }

            //阻塞等待結果,結果來了之後會調用ResponseDispatcherHandler去set結果
//            OperationResult operationResult = operationResultFuture.get();
//            //將結果列印
//            System.out.println("返回:"+operationResult);

            channelFuture.channel().closeFuture().get();

        } finally {
            group.shutdownGracefully();
        }

    }

}

Server端代碼
package com.example.nettydemo.server;

import com.example.nettydemo.server.codec.FrameDecoder;
import com.example.nettydemo.server.codec.FrameEncoder;
import com.example.nettydemo.server.codec.ProtocolDecoder;
import com.example.nettydemo.server.codec.ProtocolEncoder;
import com.example.nettydemo.server.handler.MetricsHandler;
import com.example.nettydemo.server.handler.ServerIdleCheckHandler;
import com.example.nettydemo.server.handler.ServerProcessHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.flush.FlushConsolidationHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;
import java.util.concurrent.ExecutionException;

/**
 * netty server 入口
 */
@Slf4j
public class Server {


    public static void main(String... args) throws InterruptedException, ExecutionException, CertificateException, SSLException {

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //設置channel模式,因為是server所以使用NioServerSocketChannel
        serverBootstrap.channel(NioServerSocketChannel.class);

        //最大的等待連接數量
        serverBootstrap.option(NioChannelOption.SO_BACKLOG, 1024);
        //設置是否啟用 Nagle 演算法:用將小的碎片數據連接成更大的報文 來提高發送效率。
        //如果需要發送一些較小的報文,則需要禁用該演算法
        serverBootstrap.childOption(NioChannelOption.TCP_NODELAY, true);

        //設置netty自帶的log,並設置級別
        serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));

        //thread
        //用戶指定線程名
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("boss"));
        NioEventLoopGroup workGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("worker"));
        UnorderedThreadPoolEventExecutor businessGroup = new UnorderedThreadPoolEventExecutor(10, new DefaultThreadFactory("business"));

        //只能使用一個線程,因GlobalTrafficShapingHandler比較輕量級
        NioEventLoopGroup eventLoopGroupForTrafficShaping = new NioEventLoopGroup(0, new DefaultThreadFactory("TS"));

        try {
            //設置react方式
            serverBootstrap.group(bossGroup, workGroup);

            //metrics
            MetricsHandler metricsHandler = new MetricsHandler();

            //trafficShaping流量整形
            //long writeLimit 寫入時控制, long readLimit 讀取時控制 具體設置看業務修改
            GlobalTrafficShapingHandler globalTrafficShapingHandler = new GlobalTrafficShapingHandler(eventLoopGroupForTrafficShaping, 10 * 1024 * 1024, 10 * 1024 * 1024);


            //log
            LoggingHandler debugLogHandler = new LoggingHandler(LogLevel.DEBUG);
            LoggingHandler infoLogHandler = new LoggingHandler(LogLevel.INFO);

            //設置childHandler,按執行順序放
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {

                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast("debugLog", debugLogHandler);
                    pipeline.addLast("tsHandler", globalTrafficShapingHandler);
                    pipeline.addLast("metricHandler", metricsHandler);
                    pipeline.addLast("idleHandler", new ServerIdleCheckHandler());

                    pipeline.addLast("frameDecoder", new FrameDecoder());
                    pipeline.addLast("frameEncoder", new FrameEncoder());
                    pipeline.addLast("protocolDecoder", new ProtocolDecoder());
                    pipeline.addLast("protocolEncoder", new ProtocolEncoder());

                    pipeline.addLast("infoLog", infoLogHandler);
                    //對flush增強,減少flush次數犧牲延遲增強吞吐量
                    pipeline.addLast("flushEnhance", new FlushConsolidationHandler(10, true));
                    //為業務處理指定單獨的線程池
                    pipeline.addLast(businessGroup, new ServerProcessHandler());//businessGroup,
                }
            });

            //綁定埠並阻塞啟動
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();

            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
            businessGroup.shutdownGracefully();
            eventLoopGroupForTrafficShaping.shutdownGracefully();
        }

    }

}

最後

以上介紹了Netty的基本用法,在代碼中也做了一部分的關鍵註釋,但可能還會有許多不足,也不可能滿足所有人的要求,大家可根據自己的實際需求去改造此項目。附上源碼地址netty源碼

持續學習,記錄點滴。更多文章請訪問 文章首發


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 將頁面拆分為多個組件,簡化了頁面開發,方便維護,組件也可以復用。 組件的類型 通用組件,比如表單、彈窗、菜單欄、分頁組件等 業務組件,實現某一業務的組件,比如抽獎組件 頁面組件,也叫做單頁,一個頁面就是一個組件,只完成功能,不復用 組件開發流程:聲明、註冊、使用 demo 組件使用流程 <div i ...
  • 按照國際慣例先放效果圖 項目結構搭建 首先修改app.vue <template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App' } </script> <style> * ...
  • 前面業務里有個搜索功能 , 入口比較深 , 現在想要把入口挪到有公共header的地方 , 在不想完全實現一遍功能的情況下 , 就需要模擬進行多個點擊事件來執行點擊後的效果 執行先點擊1 ,再給inout賦值 ,再點擊2 基本思路是類似jquery的trigger方法 , 原生js也是可以實現 , ...
  • 1 完整代碼下載 https://pan.baidu.com/s/1JJyVcP2KqXsd5G6eaYpgHQ 提取碼 3fzt (壓縮包名: 2020-3-24-demo.zip) 2 圖片展示 3 主要代碼 布爾運算後的物體的幾何體會自動 導入到 幾何體列表選項中, 可自由選配材質 紋理 挺簡 ...
  • 篩選組件包含一個 button 和一個 form,button 能控制 form 的顯示與隱藏。設計里 button 和 form 在一行,實現時理所當然地把這一行封裝成了一個組件。但在另一個項目里,設計有區別,button 被放到了面板的右上角,之前寫的組件沒法復用了。 ...
  • 網上統計數據,上海Web前端開發工程師這一職位的月平均收入為1.5萬元,工作經驗達到3年的web前端工程師甚至達到3萬元。 而且Web前端工程師一般工作1年左右,年薪一般就都能有15W,工作5年以上的通常能成為互聯網公司技術總監或產品經理,年薪達到25W左右。 前端工程師發展路徑: 工作1~2 年後 ...
  • JavaScript 操作 DOM 時經常會用到一些尺寸,本文介紹怪異模式和標準模式下的滾動條距離、視窗尺寸、文檔尺寸、元素文檔坐標的相容性寫法以及視窗滾動到指定位置的方法 ...
  • 內容中的{{var}}會直接顯示,使用過濾器:{{var | 過濾器名}},會先用過濾器處理var,再顯示。 按作用域劃分,有2種過濾器:全局過濾器、組件內過濾器。 demo 組件內過濾器 <div id="app"> <input v-model="content" /><br /> <!--綁定 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:在C#中,++i和i++都是自增運算符,其中++i先增加值再返回,而i++先返回值再增加。應用場景根據需求選擇,首碼適合先增後用,尾碼適合先用後增。詳細示例提供清晰的代碼演示這兩者的操作時機和實際應用。 在C#中,++i 和 i++ 都是自增運算符,但它們在操作上有細微的差異,主要體現在操作的 ...
  • 上次發佈了:Taurus.MVC 性能壓力測試(ap 壓測 和 linux 下wrk 壓測):.NET Core 版本,今天計劃準備壓測一下 .NET 版本,來測試並記錄一下 Taurus.MVC 框架在 .NET 版本的性能,以便後續持續優化改進。 為了方便對比,本文章的電腦環境和測試思路,儘量和... ...
  • .NET WebAPI作為一種構建RESTful服務的強大工具,為開發者提供了便捷的方式來定義、處理HTTP請求並返迴響應。在設計API介面時,正確地接收和解析客戶端發送的數據至關重要。.NET WebAPI提供了一系列特性,如[FromRoute]、[FromQuery]和[FromBody],用 ...
  • 原因:我之所以想做這個項目,是因為在之前查找關於C#/WPF相關資料時,我發現講解圖像濾鏡的資源非常稀缺。此外,我註意到許多現有的開源庫主要基於CPU進行圖像渲染。這種方式在處理大量圖像時,會導致CPU的渲染負擔過重。因此,我將在下文中介紹如何通過GPU渲染來有效實現圖像的各種濾鏡效果。 生成的效果 ...
  • 引言 上一章我們介紹了在xUnit單元測試中用xUnit.DependencyInject來使用依賴註入,上一章我們的Sample.Repository倉儲層有一個批量註入的介面沒有做單元測試,今天用這個示例來演示一下如何用Bogus創建模擬數據 ,和 EFCore 的種子數據生成 Bogus 的優 ...
  • 一、前言 在自己的項目中,涉及到實時心率曲線的繪製,項目上的曲線繪製,一般很難找到能直接用的第三方庫,而且有些還是定製化的功能,所以還是自己繪製比較方便。很多人一聽到自己畫就害怕,感覺很難,今天就分享一個完整的實時心率數據繪製心率曲線圖的例子;之前的博客也分享給DrawingVisual繪製曲線的方 ...
  • 如果你在自定義的 Main 方法中直接使用 App 類並啟動應用程式,但發現 App.xaml 中定義的資源沒有被正確載入,那麼問題可能在於如何正確配置 App.xaml 與你的 App 類的交互。 確保 App.xaml 文件中的 x:Class 屬性正確指向你的 App 類。這樣,當你創建 Ap ...
  • 一:背景 1. 講故事 上個月有個朋友在微信上找到我,說他們的軟體在客戶那邊隔幾天就要崩潰一次,一直都沒有找到原因,讓我幫忙看下怎麼回事,確實工控類的軟體環境複雜難搞,朋友手上有一個崩潰的dump,剛好丟給我來分析一下。 二:WinDbg分析 1. 程式為什麼會崩潰 windbg 有一個厲害之處在於 ...
  • 前言 .NET生態中有許多依賴註入容器。在大多數情況下,微軟提供的內置容器在易用性和性能方面都非常優秀。外加ASP.NET Core預設使用內置容器,使用很方便。 但是筆者在使用中一直有一個頭疼的問題:服務工廠無法提供請求的服務類型相關的信息。這在一般情況下並沒有影響,但是內置容器支持註冊開放泛型服 ...
  • 一、前言 在項目開發過程中,DataGrid是經常使用到的一個數據展示控制項,而通常表格的最後一列是作為操作列存在,比如會有編輯、刪除等功能按鈕。但WPF的原始DataGrid中,預設只支持固定左側列,這跟大家習慣性操作列放最後不符,今天就來介紹一種簡單的方式實現固定右側列。(這裡的實現方式參考的大佬 ...