【问题标题】:Play 2.5 priming the web servicePlay 2.5 启动网络服务
【发布时间】:2016-11-30 03:23:08
【问题描述】:

我有一个使用 play 2.5 框架开发的宁静 Web 服务。 我想通过调用自身来启动我的 Web 服务。这是为了确保我的服务完全启动并运行。

我采用的方法是使用eagerBinding。但是使用急切绑定注入的类中的代码会在应用启动之前执行

这是我的 Eagerbinding 代码的样子

@Singleton
class PrimingMe @Inject()(ws: WSClient) {

  isServicePrimed

  def isServicePrimed: Boolean = {

    println("PRIME ME!!!")
    val response = ws.url("http://localhost:9000/index").get
      .map {
        response =>
          response.status match {
            case 200 => true
            case _ => false
          }
      }

    try {
      Await.result(response, 5.second)
    } catch {
      case _ => false
    }

  }

}


class ServiceInjectionModule extends AbstractModule {

  def configure(): Unit = {

    bind(classOf[PrimingMe]).asEagerSingleton
  }
}

在 application.conf 中

play.modules.enabled += "util.ServiceInjectionModule"

我想用一个虚拟服务调用来启动我的应用程序,这样当真正的流量开始到来时,所有的数据库连接都会建立起来。目前,我对服务的第一次 api 调用比平时花费的时间要长得多。我还有什么其他选择可以实现这一目标。

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    没有目的不会被打败。急切加载仍然按预期工作。

    通过在 application.conf 文件的顶部声明 util.ServiceInjectionModule 来确保它是第一个加载的模块。

    看到你的问题后我做了一个小实验来证明这一点

    这就是我的模块的样子。它是在根目录中声明的,因为模块在根目录中,即应用程序,您不必显式添加到 application.conf

    class Module extends AbstractModule {
       override def configure() = {
        //It is very important for this call to be on the top.
        bind(classOf[Initialize]).asEagerSingleton()
       }
    }
    

    渴望单身

    import com.google.inject.Inject
    import com.google.inject.Singleton
    import play.api.Logger
    import play.api.libs.ws.WSClient
    
    import scala.concurrent.Await
    import scala.concurrent.duration.Duration
    
    @Singleton
    class Initialize @Inject() (wsClient: WSClient) {
    
      hit()
    
      def hit(): Unit = {
        val f = wsClient.url("http://www.google.com").get()
        val result = Await.result(f, Duration.Inf)
        Logger.info(s"status: ${result.status}")
      }
    }
    

    输出:

    [info] application - status: 200
    [info] play.api.Play - Application started (Dev)
    

    从上面的输出你可以看到Module已经加载并且hit()被调用了。

    【讨论】:

    • 为什么它必须是第一个模块?
    • 没错,它可以工作,我必须使用 sbt compile start 来启动我的应用程序。但是问题是我不能在服务开始之前这样称呼“我自己”。让我重新表述一下这个问题。
    最近更新 更多