加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在第一次调用时播放框架缓慢

发布时间:2020-12-16 18:29:18 所属栏目:安全 来源:网络整理
导读:我有一个问题,就在启动后的playframework. 我有这个简单的控制器: @Singletonclass BomberManController @Inject()(cc: ControllerComponents) extends AbstractController(cc) { def index() = Action { implicit request: Request[AnyContent] = Ok("test
我有一个问题,就在启动后的playframework.

我有这个简单的控制器:

@Singleton
class BomberManController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def index() = Action { implicit request: Request[AnyContent] =>
    Ok("test")
  }
}

在第一次调用时,在prod env上,请求需要400ms,在第二次请求需要2ms.

我不明白为什么以及如何优化.在我的项目中,请求必须少于300毫秒.

你有什么想法吗?

PlayVersion:2.6

解决方法

一种选择是创建一个虚拟Request,并通过index.apply(request)将其直接应用于控制器的构造函数中.考虑下面的warmUp方法的定义和调用点:

@Singleton 
class BomberManController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  warmUp()

  def index() = Action { implicit request: Request[AnyContent] =>
    Ok("test")   
  }

  private def warmUp() = {
    val requestFactory = new DefaultRequestFactory(HttpConfiguration())
    val request =
      requestFactory.createRequest(
        RemoteConnection("127.0.0.1",false,None),"GET",RequestTarget("/","/",Map.empty),"HTTP/1.1",Headers(),TypedMap.empty,AnyContentAsEmpty
      )
    index.apply(request)   
  } 
}

在生产中,BomberManController在应用程序启动时进行实例化,因此将调用warmUp,而warmUp又会命中索引端点.

要在本地测试此生产行为,请在application.conf中设置play.http.secret.key并使用启动应用程序

sbt clean runProd

如果您不希望使用warmUp实用程序方法污染控制器,可以将此问题分离为实用程序单例,例如WarmUpUtility,并使用eager singleton binding.例如:

@Singleton 
class WarmUpUtility @Inject()(bomberManController: BomberManController)() {

  warmUp()

  private def warmUp() = {
    val requestFactory = new DefaultRequestFactory(HttpConfiguration())
    val request =
      requestFactory.createRequest(
        RemoteConnection("127.0.0.1",AnyContentAsEmpty
      )
    bomberManController.index.apply(request)
  }

}

// Module should be in the root package 
class Module extends AbstractModule {
  override def configure() = {
    bind(classOf[WarmUpUtility]).asEagerSingleton()
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读