Play Framework 2.1 - Cannot find an implicit ExecutionContext

前端 未结 3 1552
一个人的身影
一个人的身影 2021-01-31 14:09

I am calling a webservice like this:

WS
  .url(url)
  .get
  .map { response => // error occurs on this line
    response.status match {
      case 200 =>          


        
相关标签:
3条回答
  • 2021-01-31 14:48

    Since Play 2.6 it's recommended to use guice dependency injection for execution context.

    Default execution context injection:

    Foo.scala

    class Foo @Inject()()(implicit ec:ExecutionContext) {
    
    def bar() = {
       WS.url(url)
         .get
         .map { response => // error occurs on this line
           response.status match {
             case 200 => Right(response.json)
             case status => Left(s"Problem accessing api, status '$status'")
         }
       }
    }
    

    Custom execution context injection:

    application.conf

    # db connections = ((physical_core_count * 2) + effective_spindle_count)
    fixedConnectionPool = 9
    
    database.dispatcher {
      executor = "thread-pool-executor"
      throughput = 1
      thread-pool-executor {
        fixed-pool-size = ${fixedConnectionPool}
      }
    }
    

    DatabaseExecutionContext.scala

    @Singleton 
    class DatabaseExecutionContext @Inject()(system: ActorSystem) extends CustomExecutionContext(system,"database.dispatcher")
    

    Foo.scala

    class Foo @Inject()(implicit executionContext: DatabaseExecutionContext ) {   ...    }
    

    More info at:

    https://www.playframework.com/documentation/2.6.x/Migration26#play.api.libs.concurrent.Execution-is-deprecated https://www.playframework.com/documentation/2.6.x/Highlights26#CustomExecutionContext-and-Thread-Pool-Sizing

    0 讨论(0)
  • 2021-01-31 14:56

    An alternative option:

    import scala.concurrent.ExecutionContext.Implicits.global
    
    0 讨论(0)
  • 2021-01-31 14:58

    According to this issue, it is fixed in the documentation. I needed to add the following import:

    import play.api.libs.concurrent.Execution.Implicits._
    
    0 讨论(0)
提交回复
热议问题