实现重新加载Typesafe配置的好方法是什么

时间:2014-08-13 07:03:46

标签: java scala concurrentmodification typesafe-config

在使用Typesafe Config的Scala应用程序中,我想添加在运行时重新加载Config的可能性。 Config实例是不可变的。以下是我到目前为止的情况:

package config

trait Settings {
  private[config] var config: Config = ConfigFactory.empty()
  def engine: EngineSettings
}

trait EngineSettings {
  def weight: Int
  def offset: Int
}

class AppSettings {
  override def engine = new EngineSettings {
    override def weight = config.getInt("engine.weight")
    override def offset = config.getInt("engine.offset")
  }
}

object Settings {
  private val namedSettings = new TrieMap[String, AppSettings]
  def load(configName: String = "local"): Settings = {
    // load config
    // create or update AppSettings
    // add to map and return
  }
}

最初使用Settings.load创建一个Settings实例。该实例引用将传递给其他类。然后第二个线程可以通过再次调用Settings.load来重新加载底层配置。您可以通过以下方式访问它:

class Engine(settings: Settings) {
  def calculate() = {
    val weight = settings.engine.weight
    // do some stuff
    val offset = settings.engine.offset
  }
}

有两个问题:

  1. 有人可能会重新加载底层配置,而calculate()是在行://做一些事情(一致性)
  2. 不喜欢在“设置特征”中使用var
  3. 如何改进此设计:)

1 个答案:

答案 0 :(得分:4)

您可以将config转换为支持配置缓存失效(以及合理默认值)的方法,因此您可以选择动态(以下示例中的默认值)和性能。

一般情况下,我建议你使用TypeSafe的Config的一个好的Scala类型安全包装器,例如Ficus(例如Gradle-stype artifact dependency net.ceedubs:ficus_2.11:1.1.1

package config

import scala.collection.concurrent.TrieMap

import com.typesafe.config.{Config, ConfigFactory}
import net.ceedubs.ficus.Ficus._

trait Settings {
  protected[config] def config (
    name: String = "local",
    invalidateCache: Boolean = false
  ): Config = {
    if (invalidateCache) { ConfigFactory invalidateCaches }
    ConfigFactory load name
  }
  def engine: EngineSettings
}

trait EngineSettings {
  def weight: Int
  def offset: Int
}

class AppSettings(val name: String = "local") extends Settings {
  val c = config()

  override def engine = new EngineSettings {
    override def weight = c.as[Int]("engine.weight")
    override def offset = c.as[Int]("engine.offset")
  }
}

object Settings {
  private val namedSettings = new TrieMap[String, AppSettings]
  def load(configName: String = "local"): Settings = {
    // e.g.
    val loadedUpToDate = new AppSettings
    namedSettings +=
      ((configName + "." + System.currentTimeMillis, loadedUpToDate))
    new Settings {
      override def engine = loadedUpToDate.engine
    }
  }
}

我认为这可以解决您的问题,因为:

  1. 默认情况下,通过重新加载
  2. ,配置检索是动态的
  3. 通过使用方法,您不会求助于可变状态