gpt4 book ai didi

java - spray scala构建非阻塞servlet

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:20:10 27 4
gpt4 key购买 nike

我使用 spray 和 akka actor 构建了一个 scala 应用程序。

我的问题是请求是同步的,服务器不能同时管理很多请求。

这是正常行为吗?我该怎么做才能避免这种情况?

这是我的启动代码:

object Boot extends App with Configuration {

// create an actor system for application
implicit val system = ActorSystem("my-service")
//context.actorOf(RoundRobinPool(5).props(Props[TestActor]), "router")
// create and start property service actor
val RESTService = system.actorOf(Props[RESTServiceActor], "my-endpoint")

// start HTTP server with property service actor as a handler
IO(Http) ! Http.Bind(RESTService, serviceHost, servicePort)
}

Actor 代码:

class RESTServiceActor extends Actor 
with RESTService {
implicit def actorRefFactory = context

def receive = runRoute(rest)
}



trait RESTService extends HttpService with SLF4JLogging{
val myDAO = new MyDAO



val AccessControlAllowAll = HttpHeaders.RawHeader(
"Access-Control-Allow-Origin", "*"
)
val AccessControlAllowHeadersAll = HttpHeaders.RawHeader(
"Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"
)
val rest = respondWithHeaders(AccessControlAllowAll, AccessControlAllowHeadersAll) {
respondWithMediaType(MediaTypes.`application/json`){
options {
complete {
""
}
} ~
path("some"/"path"){
get {
parameter('parameter){ (parameter) =>
ctx: RequestContext =>
handleRequest(ctx) {
myDAO.getResult(parmeter)
}
}
}
}
}
}

/**
* Handles an incoming request and create valid response for it.
*
* @param ctx request context
* @param successCode HTTP Status code for success
* @param action action to perform
*/
protected def handleRequest(ctx: RequestContext, successCode: StatusCode = StatusCodes.OK)(action: => Either[Failure, _]) {
action match {
case Right(result: Object) =>
println(result)
ctx.complete(successCode,result.toString())
case Left(error: Failure) =>
case _ =>
ctx.complete(StatusCodes.InternalServerError)
}
}
}

我看到了:

Akka Mist provides an excellent basis for building RESTful web services in Scala since it combines good scalability (enabled by its asynchronous, non-blocking nature) with general lightweight-ness

这就是我所缺少的吗? spray 是默认使用它还是我需要添加它,如何添加?

我对此有点困惑。任何帮助表示赞赏。

最佳答案

如果您是从头开始,我建议使用 Akka HTTP,记录在 http://doc.akka.io/docs/akka-stream-and-http-experimental/1.0-M4/scala/http/ .它是 Spray 的一个端口,但使用 Akka Streams,这将是重要的进步。

就使您的代码完全异步而言,关键模式是将 Future 返回到您的结果,而不是结果数据本身。换句话说,RESTServiceActor 应该返回一个返回数据的 Future,而不是实际数据。这将允许 Spray/Akka HTTP 接受额外的连接,服务参与者的异步完成将在完成时返回结果。

关于java - spray scala构建非阻塞servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29875754/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com