Skip to content

Instantly share code, notes, and snippets.

@halfhp
Last active August 14, 2018 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halfhp/3f9426510fe6f53465c7669f3031b8f3 to your computer and use it in GitHub Desktop.
Save halfhp/3f9426510fe6f53465c7669f3031b8f3 to your computer and use it in GitHub Desktop.
Play Framework Remote Configuration
package your.package
import scala.concurrent.duration._
import play.api.{ApplicationLoader, Configuration}
import play.api.inject.guice.{GuiceApplicationBuilder, GuiceApplicationLoader}
import scala.concurrent.{Await, Future}
class MyAppLoader extends GuiceApplicationLoader() {
override def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
// we're forced to use this form of Configuration because internally, Play requires
// an instance that implements [[MergeableValue]] which is not available to us for
// building our own implementations.
// TODO: move the data mapping somewhere else
val extra = Configuration("remote.welcomeMessage" -> remoteConfig.fetchWelcomeMessage())
initialBuilder
.in(context.environment)
.loadConfig(extra ++ context.initialConfiguration)
.overrides(overrides(context): _*)
}
}
object remoteConfig {
/**
* Retrieve the welcome message from a network resource, etc
* @return
*/
def fetchWelcomeMessage(): String = {
import scala.concurrent.ExecutionContext.Implicits.global
// pointless use of a future with an await to simulate what an actual call to an async
// resource would look like; have to await here because there's no way to asynchronously
// supply configuration values to the Configuration instance above.
Await.result(Future {
"I came from space!!!"
}, 10.seconds)
}
}
@halfhp
Copy link
Author

halfhp commented Aug 14, 2018

You also need to configure this as the app's new application loader in your application.conf:

play.application.loader = "your.package.MyAppLoader"

Now, you can use remote params like any other in your app:

Logger.info(configuration.get[String]("remote.welcomeMessage"))

screen shot 2018-08-14 at 11 18 13 am

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment