The code below prints '1' and never prints '2', as a result the browser hangs when it requests the page served by the index
method. The future is never invoked. If the future.map
statement is replaced with Await.result(future, Duration.Inf)
the code works correctly. What is the problem?
case class UserRole (sk: Int, name: String)
class UserRoleDB(tag: Tag) extends Table[UserRole](tag, "user_roles") {
def sk = column[Int]("sk", O.PrimaryKey)
def name = column[String]("name")
def * = (sk, name) <> ((UserRole.apply _).tupled, UserRole.unapply)
}
class Test extends Controller {
def index = Action.async { request =>
val db = Database.forConfig("db1")
val userRoles = TableQuery[UserRoleDB]
val ur = UserRole(1002,"aaa")
try {
val action = (for {
userRole2 <- userRoles += ur
} yield (userRole2)).transactionally
val future = db.run(action)
println(1)
// val result = Await.result(future, Duration.Inf)
future.map { result => {
println(2)
Ok("Finished OK")
}
}
}
finally db.close
}
}
答案 0 :(得分:0)
首先,您不应该在每个http请求上创建数据库连接。 第二个你的finally子句可能在你未来有可能被执行之前执行,这可能是你问题的原因。
除此之外,它看起来不错。尝试在应用程序启动时或通过DI初始化资源,在应用程序停止时关闭数据库,然后查看问题是否仍然存在。