Slick Transactionally future is not invoked in Play for Scala [duplicate]

大兔子大兔子 提交于 2019-12-13 08:20:05

问题


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

  }
}

回答1:


First of all you shouldn't create db connection on each http request. Second your finally clause executes probably before you future has chance to be executed and this may be the reason of your problem.

Other than that, it's looking good. Try to initialize resource on application startup or via DI, close db on application stop and then see if problem still occurs.



来源:https://stackoverflow.com/questions/40925036/slick-transactionally-future-is-not-invoked-in-play-for-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!