scala - 在 Scala 中保持全局应用程序状态的好策略是什么?

标签 scala slick

作为一个最简单的例子,假设我在某种模式下启动我的应用程序(例如测试),那么我希望能够在应用程序的其他部分中检查我正在运行的模式。这应该是非常重要的很简单,但我正在寻找全局变量的正确 Scala 替代品。请给我更多的信息:“Scala 对象就像全局变量”

理想的解决方案是在启动时,应用程序将创建一个对象,并在创建时设置该对象的“模式”。之后,应用程序的其他部分将只能读取“模式”的状态。如何在不传递对整个应用程序中对象的引用的情况下执行此操作?

我的真实场景实际上包括诸如在启动时选择数据库名称或单例数据库对象之类的事情,并且之后不允许任何其他内容更改该对象。一个问题是我试图在不传递对数据库的引用的情况下实现这一目标。

更新:

这是我想做的事情以及我当前的解决方案的一个简单示例:

object DB{
  class PDB extends ProductionDB
  class TDB extends TestComplianceDB
  lazy val pdb = new PDB
  lazy val tdb = new TDB
  def db = tdb //(or pdb) How can I set this once at initialisation?
}

因此,我创建了不同的数据库配置作为特征。根据我是在测试模式还是生产模式下运行,我想使用正确的配置,其中配置如下所示:

trait TestDB extends DBConfig {
  val m = new Model("H2", new DAL(H2Driver),
    Database.forURL("jdbc:h2:mem:testdb", driver = "org.h2.Driver"))

  // This is an in-memory database, so it will not yet exist.
  dblogger.info("Using TestDB")
  m.createDB
}

所以现在,每当我使用数据库时,我都可以这样使用它:

val m = DB.db.m
m.getEmployees(departmentId)

我的问题实际上是,这种风格是坏、好还是可以(使用单例来保存数据库句柄)。我正在使用 Slick,我认为这与仅运行一个 Slick 实例有关。这是否会导致可扩展性问题。

有没有更好的方法来解决这个问题?

最佳答案

您可以使用typesafe config library ,这也用在 Play 和 Akka 等项目中。 Play 和 Akka 文档都解释了其用法的基本部分。来自 Play documentation (Additional configuration)

Specifying alternative configuration file

The default is to load the application.conf file from the classpath. You can specify an alternative configuration file if needed:

Using -Dconfig.resource

-Dconfig.resource=prod.conf

Using -Dconfig.file

-Dconfig.file=/opt/conf/prod.conf

Using -Dconfig.url

-Dconfig.url=http://conf.mycompany.com/conf/prod.conf

Note that you can always reference the original configuration file in a new prod.conf file using the include directive, such as:

include "application.conf"

key.to.override=blah

关于scala - 在 Scala 中保持全局应用程序状态的好策略是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15492600/

相关文章:

scala - 何时使用选项

scala - 在 scala 中估计 PI 的单子(monad)方法

scala - 如何返回 Id 的序列生成

scala - 查看 Scala 反射中的注释

scala - Null 类型的表达式不符合隐式转换的条件

xml - Scala 2.8.0中如何将二维数组写入xml

postgresql - 如何在保存为 Instant 的 Play-SLICK 中过滤日期?

mysql - 无法让 Scala、Slick 和 MySQL 协同工作

scala - 有没有办法删除 Slick GetResult 中的样板文件?

scala - 玩光滑 : How to inject DbConfigProvider in tests