How is Ostrich used for configuration?

前端 未结 1 1803
遥遥无期
遥遥无期 2021-02-02 14:40

I need a way to configure my scala application. Configgy seemed the way to go in Scala but it is deprecated https://github.com/robey/configgy#readme and now this functionality i

相关标签:
1条回答
  • 2021-02-02 15:18

    I'd like to know the official answer as well, but nobody answered so I decided to poke around. Sorry if this answer isn't quite comprehensive.

    The best example I found was in com.twitter.ostrich.admin.RuntimeEnvironment, especially if you look mainly at loadConfig.

    Say you want to configure an instance of class T. The basic idea is as follows:

    • Get a java.io.File that contains Scala source code that evaluates to a com.twitter.util.Config[T].
    • In order to be a valid Config[T] you'll need to have a def apply(): T method. To keep the implementation details out of the config file, you'll want to define a class in your project that extends Config[T]. You can also use this class to define default/required fields.
    • Instantiate a new com.twitter.util.Eval instance, and call apply(file) to get a Config[T] instance.
    • Call config.validate() to throw the proper exceptions for malformed config files.
    • Call config.apply() to get your fully configured instance of T.

    Here is a simple example, where I configure a new WidgetService:

    class WidgetService(val port: Int)
    
    class WidgetConfig extends com.twitter.util.Config[WidgetService] {
      var port = required[Int]
      def apply(): WidgetService = {
        new WidgetService(port)
      }
    }
    
    object MyApp extends App {
      val configFile = new java.io.File("mywidget_config.scala")
      val eval = new com.twitter.util.Eval
      val config = eval[com.twitter.util.Config[WidgetService]](configFile)
      config.validate()
      val widgetService = config()
      println(widgetService.port)
    }
    

    And here is mywidget_config.scala:

    new WidgetConfig {
      port = 8000
    }
    

    Note: you may have to make modifications if you put this in a package. I did everything in the default package for brevity.

    To get the dependencies to work, I added this to my SBT config:

    libraryDependencies += "com.twitter" % "util" % "1.10.1"
    
    0 讨论(0)
提交回复
热议问题