如何在 Gradle 中添加 Netty 和 RXTX 的原生依赖?

How to add native dependencies for Netty and RXTX in Gradle?

在我的应用程序中,我想与 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'
  ...
}

现在编译时依赖性已经解决,我可以毫无错误地构建项目。

我的构建配置使用以下命令生成了一个可执行 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)
    }
  }
}

但是因为 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)

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

librxtxSerial.jnilib(对于OSX)

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

我现在通过使用 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'

  ...
}

库 'jbidibc-rxtx-2.2' 使用另一种加载机制从 'bidib-rxtx-binaries' 加载二进制文件。这就是它现在起作用的原因。

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

configurations {
  all*.exclude group: 'org.rxtx'
}