问题描述
当我使用 Spray.io 开发 RESTful API 时,我应该如何构建我的应用程序?
When I'm using Spray.io to develop a RESTful API, how should I structure my application?
我已经看到了关于如何拆分 Spray 应用程序的这个答案,但我对此并不满意,因为它似乎没有使用每个请求一个参与者"的方法.我是否可以根据路径将来自根 Actor 的请求转发到我的应用程序中的其他 Actor,并在这些 Actor 内部定义相关路由?
I already saw this answer on how to split a Spray application, but I'm not satisfied with it, since it doesn't seem to use the "one actor per request" approach. Can I forward requests from the root actor to other actors in my application based on paths and, inside these actors, define the related routes?
谢谢
推荐答案
您当然可以根据路径或其他任何方式将请求从一个参与者转发到另一个参与者.查看我的示例项目(这是一个示例项目的一个分支的分支):
You can certainly forward requests from one actor to another, based on paths or whatever else. Check out my example project (which is a fork of a fork of an example project):
来自主要参与者的相关代码,用于接收所有请求并将它们路由到处理每个服务的其他参与者:
Relavent code from the main actor that receives all requests and routes them to other actors that handle each service:
def receive = runRoute {
compressResponseIfRequested(){
alwaysCache(simpleCache) {
pathPrefix("movies") { ctx => asb.moviesRoute ! ctx } ~
pathPrefix("people") { ctx => asb.peopleRoute ! ctx }
} ~
pathPrefix("login") { ctx => asb.loginRoute ! ctx } ~
pathPrefix("account") { ctx => asb.accountRoute ! ctx }
}
}
例如电影路线:
def receive = runRoute {
get {
parameters('query, 'page ? 1).as(TitleSearchQuery) { query =>
val titleSearchResults = ms.getTitleSearchResults(query)
complete(titleSearchResults)
}~
path(LongNumber) { movieId =>
val movie = ms.getMovie(movieId)
complete(movie)
}~
path(LongNumber / "cast") { movieId =>
val movieCast = ms.getMovieCast(movieId)
complete(movieCast)
}~
path(LongNumber / "trailers") { movieId =>
val trailers = ms.getTrailers(movieId)
complete(trailers)
}
}
}
这篇关于如何使用 Spray.io 构建 RESTful API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!