首页 > 解决方案 > 如何根据操作系统有条件地加载特定库?

问题描述

我正在加载一个 netty 库,具体取决于我是在开发服务器还是生产服务器(OSX 与 linux)

val nettyEpoll        = "io.netty"                   % "netty-transport-native-epoll"  % nettyVersion classifier "linux-x86_64"
  val nettyKqueue       = "io.netty"                   % "netty-transport-native-kqueue" % nettyVersion classifier "osx-x86_64"

现在在我的代码中,我将如何根据当前运行的操作系统加载正确的类?

在我的代码中,我有:

  val workerGroup =
      new KQueueEventLoopGroup

如果这是 linux 我需要加载NioEventLoopGroup.

当我创建生产版本时,有没有办法加载正确的?

如果我在我的 OSX 笔记本电脑上构建,有没有办法告诉编译器为 linux 构建?

标签: scalasbt

解决方案


要检查代码中的操作系统版本,您可以使用 java functionSystem.getProperty("os.name")之类的

def getWorkerGroup(): EventLoopGroup = {
    System.getProperty("os.name").toLowerCase match {
        case mac if mac.contains("mac")  => new KQueueEventLoopGroup()
        case linux if linux.contains("linux") => new NioEventLoopGroup()
  }
}

在 sbt build 中,您可以使用相同的函数来选择要使用的库:

val configureDependencyByPlatform = settingKey[ModuleID]("Dynamically change reference to the jars dependency depending on the platform")
configureDependencyByPlatform := {
  System.getProperty("os.name").toLowerCase match {
    case mac if mac.contains("mac")  => "org.example" %% "somelib-mac" % "1.0.0"
    case linux if linux.contains("linux") => "org.example" %% "somelib-linux" % "1.0.0"
    case osName => throw new RuntimeException(s"Unknown operating system $osName")
  }
}

如果您想手动选择您需要的构建,您可以添加某种可选参数,并在获取os.name.


推荐阅读