2017-05-04 87 views
0

我是一般的Akka HTTP和Scala的新手。我正在嘗試使用Akka actors來處理HTTP請求。當遇到HTTP請求時,相應的子actor被激活。目前,這是我的演員邏輯:如何使用Akka actors來處理Akka中的HTTP請求

trait CorsDirective extends BasicDirectives { actor: Actor => 

    private def createResponder(requestContext: RequestContext) = { 
    context.actorOf(Props(new CorsResponder(requestContext))) 
    } 

    val corsRoute = { 
    path("corsdirective") { 
     get { 
     requestcontext => 
      val corsresponder = createResponder(requestcontext) 
      corsresponder ! "corsdirectiveactiviated" 
     } 
    } 
    } 
} 

class CorsResponder(requestcontext: RequestContext) extends Actor { 

    override def receive: Receive = { 
    case String => requestcontext.complete("The cors directive was called here") 
    } 
} 

現在我怎麼插到我的主要程序,該程序是這樣的:

​​

回答

0

當您CorsResponder收到一條消息,要回復給發件人。所以,做這樣的事情:

class CorsResponder(requestcontext: RequestContext) extends Actor { 

    override def receive: Receive = { 
    case String => sender ! "The cors directive was called here" 
    } 
} 

使用ask模式來完成您的請求:

import akka.pattern.ask 
import context.dispatcher // You will want to pass it to corsRoute as its argument 

(corsresponder ? "corsdirectiveactiviated").mapTo[String] { result => 
    case message => complete(message) 
} 
+0

嗨@Branislav,我想知道怎麼我的主要方法是看?謝謝 – BigDataScholar