在使用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
}
}
有两个问题:
如何改进此设计:)
答案 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
}
}
}
我认为这可以解决您的问题,因为: