【问题标题】:PlayFramework 2.6 shutdown hookPlayFramework 2.6 关闭钩子
【发布时间】:2018-01-24 16:29:06
【问题描述】:

播放框架 2.6
Mongo 3.6.2
Mongo Scala 驱动程序 2.2.0

每次关闭应用程序时,我都想删除 MongoDB 数据库。我有以下代码,实现生命周期停止挂钩,但是当 SIGTERM 发送到应用程序时,它不会删除数据库。我做错了什么?

@Singleton
class Repo  @Inject() (lifecycle: ApplicationLifecycle) {

  val codecRegistry: CodecRegistry = fromRegistries(fromProviders(classOf[MyCollection]), DEFAULT_CODEC_REGISTRY )
  val mongoClient: MongoClient = MongoClient()
  val database: MongoDatabase =   mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry)

 .......

 lifecycle.addStopHook { () => {
     database.drop().toFuture()
       }
     }   
   }

【问题讨论】:

  • 我不确定drop() 是如何实现的,但我猜想——您可能需要使用超时阻止调用,而不是使用toFuture()
  • 你确定关闭钩子被执行了吗?

标签: mongodb scala playframework playframework-2.6


【解决方案1】:

等待数据库删除Future完成(并关闭MongoClient):

import java.util.concurrent.TimeUnit

import scala.concurrent.Await
import scala.concurrent.duration.Duration

...

lifecycle.addStopHook { () =>
  val result = Await.result(database.drop().toFuture(), Duration(10, TimeUnit.SECONDS))
  Future.successful(mongoClient.close())
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2023-03-19
    • 1970-01-01
    • 2018-04-21
    • 2019-10-22
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多