0

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()
       }
     }   
   }
4

1 回答 1

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())
}
于 2018-01-24T19:26:35.153 回答