PlayFramework 2.6关闭钩子

时间:2018-01-24 16:29:06

标签: mongodb scala playframework playframework-2.6

Play Framework 2.6
Mongo 3.6.2
Mongo Scala Driver 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()
       }
     }   
   }

1 个答案:

答案 0 :(得分: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())
}
相关问题