玩2.5启动Web服务

时间:2016-11-29 05:42:45

标签: scala playframework

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

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

这是我的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呼叫需要比平常更长的时间。我还有什么其他选择来实现这一目标。

1 个答案:

答案 0 :(得分:2)

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

确保correct_btn.DialogResult = DialogResult.OK; 是第一个要加载的模块,方法是在application.conf文件的顶部声明它。

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

这就是我的模块的样子。它在根目录中声明,并且作为Module在根导向器中,即app,您不必显式添加到application.conf

util.ServiceInjectionModule

渴望单身人士

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) 被调用。