加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用SecureSocial进行播放:在单独的线程池中运行DB IO

发布时间:2020-12-16 08:54:02 所属栏目:安全 来源:网络整理
导读:我有一个Play 2.2.1应用程序,它使用 play-slick 0.5.0.8将数据持久保存到Postgresql后端,使用 SecureSocial 2.1.2来处理用户授权. 由于play-slick事务是阻塞的,我在/conf/application.conf文件中创建了一个单独的slick-context执行上下文,如instructions fou
我有一个Play 2.2.1应用程序,它使用 play-slick 0.5.0.8将数据持久保存到Postgresql后端,使用 SecureSocial 2.1.2来处理用户授权.

由于play-slick事务是阻塞的,我在/conf/application.conf文件中创建了一个单独的slick-context执行上下文,如instructions found in the plugin’s Wiki所示:

play {
  akka {
    actor {
      slick-context = {
        fork-join-executor {
          parallelism-min = 300
          parallelism-max = 300
        }
      }
    }
  }
}

这允许我创建一个在单独的执行上下文中运行的控制器Action,并且不会阻止默认线程池中的线程.例如. /app/controllers/Application.scala:

示例一 – 使用play-slick的DBAction:

import play.api.db.slick._
object Application extends Controller{ 

  // this controller Action won't block threads in the default pool since DBAction uses my separate slick-context execution context
  def recipes = DBAction { implicit rs =>
    val recipes  = Query(Recipes).list
    Ok(recipes.mkString)
  }

}

对于某些控制器操作,我希望能够将SecureSocial的操作(SecuredAction,UserAwareAction等)与play-slick的DBAction结合使用.将两者结合起来的最佳方法是什么?

我意识到我可以做类似下面的事情,但我的理解是DB调用不会使用我单独的光滑上下文,因此会阻止默认的线程池:

示例二 – 使用SecureSocial的操作:

import play.api.db.slick._
import securesocial.core._
object Application extends Controller{ 

  // changing from a DBAction to a SecuredAction so that I can use SS's goodies
  def recipes = SecuredAction { implicit request =>
    val recipes  =  DB.withSession { implicit session:Session => Query(Recipes).list } // i'm guessing this WILL BLOCK the default thread pool since it isn't using my separate slick-context execution context??
    Ok(recipes.mkString)
  }

}

假设示例二将使用/阻止默认线程池而不是单独的光滑上下文线程池,我是否正确?如果是这样,有没有办法改变这个?

我显然可以通过bumping up Play’s default thread pool(默认调度程序)解决这个问题,但理想情况下我希望保持默认线程池非常精简,并在单独的池中运行所有阻塞数据库调用.

协助赞赏!

解决方法

要回答你的问题,

Am I correct in assuming that Example Two will use/block the default
thread pool instead of my separate slick-context thread pool? If so,

是的,那会耗尽/阻止默认池.

如果你想使用单独的光滑上下文线程池,那你可以试试这样的东西吗?

import scala.concurrent.Future

  // Note the use of '.async' |
  //                          V
  def recipes = SecuredAction.async { implicit request =>
    Future { // your code that may block
      val recipes  =  DB.withSession { implicit s:Session => 
        Query(Recipes).list 
      } 
      Ok(recipes.mkString)
    } 
  }

Future期望一个ExecutionContext(隐式会做);所有你需要传递一个play-slick使用的(隐式):

import play.api._
implicit val slickExecutionContext = 
  Akka.system.dispatchers.lookup("play.akka.actor.slick-context")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读