scala - 如何根据操作系统有条件地加载特定库?
问题描述
我正在加载一个 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 构建?
解决方案
要检查代码中的操作系统版本,您可以使用 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
.
推荐阅读
- ios - PJSIP 调用 pjsua_destroy() 阻塞主线程
- python - 从音频字节创建 wav 文件
- kubernetes - 在集群内部使用 Istio VirtualService
- google-cloud-platform - 当我在脚本中使用连接时,GCP BigQuery 消息“未找到:连接”
- php - 一个接收正数的PHP数组函数,返回最大值,如果数组为空则返回0
- python - 在脚本的其余部分使用选定的文件
- github - 已解决:从 Heroku 仪表板连接到 Github 时出错
- html - 如何通过纯 CSS 为电子邮件客户端设置以省略号结尾的线夹?
- web - 交互式元素(锚标签)在 ipad 中滑动时没有获得焦点并带有画外音
- c# - 如何以编程方式单击 TextBlock?