原生傳輸
Netty 提供以下針對特定平台的 JNI 傳輸機制
- Linux(從 4.0.16 開始)
- MacOS/BSD(從 4.1.11 開始)
這些 JNI 傳輸機制新增了針對特定平台的功能,產生較少的垃圾,相比於 NIO 基礎傳輸機制,通常可提升效能。
請注意,您必須為相依關係指定適當的分級器,以確保包含對應的原生函式庫。
由於原生傳輸機制與 NIO 傳輸機制相容,您只需執行以下搜尋和取代
-
NioEventLoopGroup
→EpollEventLoopGroup
-
NioEventLoop
→EpollEventLoop
-
NioServerSocketChannel
→EpollServerSocketChannel
-
NioSocketChannel
→EpollSocketChannel
由於原生傳輸機制並非 Netty 核心的一部分,所以您需要在 Maven pom.xml
中,或是您建構系統中的等效資源中,將 netty-transport-native-epoll
拉入為相依關係
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<version>${project.version}</version>
<classifier>linux-x86_64</classifier>
</dependency>
...
</dependencies>
在上面的內容中,分類器是 linux-x86_64
,表示依賴關係中包含的原生二進檔案是為 Linux 編譯,在 64 位元 x86 CPU 上執行。其他 CPU 架構和一些特定的 Linux 發行版需要不同的分類器。
注意:官方的 Linux 組建都連結到 GLIBC。這表示使用 Musl 作為其 libc 實作的作業系統不受 Netty 原生傳輸的官方組建支援。如果您想在不受支援的 CPU 架構或 libc 實作上使用 Netty 原生傳輸,您需要自行組建。請參閱下方說明如何執行此作業。
若要在 sbt 專案中使用原生傳輸,請在您的 libraryDependencies
中加入下列程式碼:
"io.netty" % "netty-transport-native-epoll" % "${project.version}" classifier "linux-x86_64"
由於原生傳輸機制與 NIO 傳輸機制相容,您只需執行以下搜尋和取代
-
NioEventLoopGroup
→KQueueEventLoopGroup
-
NioEventLoop
→KQueueEventLoop
-
NioServerSocketChannel
→KQueueServerSocketChannel
-
NioSocketChannel
→KQueueSocketChannel
由於原生傳輸並不屬於 Netty 核心,您需要在您的 Maven pom.xml
中加入 netty-transport-native-kqueue
作為依賴關係。
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-kqueue</artifactId>
<version>${project.version}</version>
<classifier>osx-x86_64</classifier>
</dependency>
...
</dependencies>
若要在 sbt 專案中使用原生傳輸,請在您的 libraryDependencies
中加入下列程式碼:
"io.netty" % "netty-transport-native-kqueue" % "${project.version}" classifier "osx-x86_64"
如果您已經有原生傳輸的 JAR 檔案,您不需要自行組建原生傳輸,因為 JAR 檔案已包含必要的共享函式庫檔案(例如 .so
、.dll
、.dynlib
),並且它們會自動載入。
若要組建原生傳輸,您需要使用具有 64 位元核心 2.6 或更高版本的 Linux。請也安裝所需的工具和函式庫
# RHEL/CentOS/Fedora:
sudo yum install autoconf automake libtool make tar \
glibc-devel \
libgcc.i686 glibc-devel.i686
# Debian/Ubuntu:
sudo apt-get install autoconf automake libtool make tar \
gcc
若要組建原生傳輸,您需要使用 MacOS 10.12 或更高版本。請也安裝所需的工具和函式庫
brew install autoconf automake libtool