如何在 Gradle 中为 Netty 和 RXTX 添加本机依赖项?

Tob*_*ler 5 java native rxtx gradle netty

在我的应用程序中,我想与 Arduino 板进行一些通信。为了实现串口通信,我想结合使用Netty框架和RXTX传输库。

所以我在 Gradle 构建配置中添加了以下几行:

dependencies {
  compile group: 'io.netty', name: 'netty-all', version: '4.1.5.Final'
  compile group: 'io.netty', name: 'netty-transport-rxtx', version: '4.1.5.Final'
  ...
}
Run Code Online (Sandbox Code Playgroud)

现在解决了编译时依赖项,我可以构建项目而不会出现任何错误。

我的构建配置使用以下命令生成了一个可执行 JAR:

jar {
  manifest {
    attributes  'Main-Class': 'de.project.Main',
                'Implementation-Title': 'My Project',
                'Implementation-Version': version
  }
  from {
    configurations.compile.collect {
        it.isDirectory() ? it : zipTree(it)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是因为 RXTX 库使用本机库,所以在执行代码时出现以下异常:

java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: no rxtxSerial in java.library.path
  at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
  at java.lang.Runtime.loadLibrary0(Runtime.java:870)
  at java.lang.System.loadLibrary(System.java:1122)
  at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
  at de.project.communication.SerialConnector.getSerialPorts(SerialConnector.java:83)
  at de.project.Main.main(Main.java:36)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:497)
  at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Run Code Online (Sandbox Code Playgroud)

异常告诉我,我需要 RXTX 的平台相关本机库,例如:

librxtxSerial.jnilib(用于 OSX)

所以我的问题是:将本机库添加到我的 Gradle 构建中的最佳实践是什么?在 IDE 之外运行我的项目时,如何告诉 IntelliJ 也使用这些本机库?到目前为止,我还没有在互联网上找到任何令人满意的答案。

Tob*_*ler 3

我现在通过使用 RXTX 库的附加依赖项解决了这个问题:

我添加了两个依赖项:

dependencies {
  compile group: 'io.netty', name: 'netty-all', version: '4.1.5.Final'
  compile group: 'io.netty', name: 'netty-transport-rxtx', version: '4.1.5.Final'

  // New dependencies:
  compile group: 'org.bidib.jbidib', name: 'jbidibc-rxtx-2.2', version: '1.6.0'
  compile group: 'org.bidib.jbidib', name: 'bidib-rxtx-binaries', version: '2.2'

  ...
}
Run Code Online (Sandbox Code Playgroud)

库“jbidibc-rxtx-2.2”使用另一种加载机制来从“bidib-rxtx-binaries”加载二进制文件。这就是它现在有效的原因。

因为“netty-transport-rxtx”已经提供了 RXTX 库作为依赖项,所以我添加了以下配置,以便在我的项目中仅使用“新”RXTX 库。

configurations {
  all*.exclude group: 'org.rxtx'
}
Run Code Online (Sandbox Code Playgroud)