在Play for Scala中不会调用Slick Transactionally Future [英] Slick Transactionally future is not invoked in Play for Scala

查看:93
本文介绍了在Play for Scala中不会调用Slick Transactionally Future的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码显示"1",从不显示"2",因此,当浏览器请求由index方法提供服务的页面时,浏览器将挂起.永远不会调用未来.如果将future.map语句替换为Await.result(future, Duration.Inf),则代码将正常工作.有什么问题吗?

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

  }
}

推荐答案

首先,您不应该在每个http请求上创建数据库连接. 其次,您的finally子句可能在您将来有机会执行之前执行,这可能是您遇到问题的原因.

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.

除此之外,它看起来还不错.尝试在应用程序启动时或通过DI初始化资源,在应用程序停止时关闭db,然后查看问题是否仍然出现.

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.

这篇关于在Play for Scala中不会调用Slick Transactionally Future的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆