Spray.io 路由可以拆分成多个“控制器"吗? [英] Can Spray.io routes be split into multiple "Controllers"?
本文介绍了Spray.io 路由可以拆分成多个“控制器"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我还没有找到将 Spray.io 路由拆分为多个文件的可靠示例或结构.我发现我的路由的当前结构将变得非常繁琐,对于一个非常简单的 REST API 应用程序,最好将它们抽象为不同的控制器".
I haven't found a solid example or structure to splitting up Spray.io routes into multiple files. I am finding that the current structure of my routes are going to become very cumbersome, and it would be nice to abstract them into different "Controllers" for a very simple REST API app.
文档似乎没有太大帮助:http://spray.io/文档/喷雾路由/关键概念/指令/#directives
Docs don't seem to help too much: http://spray.io/documentation/spray-routing/key-concepts/directives/#directives
这是我目前所拥有的:
class AccountServiceActor extends Actor with AccountService {
def actorRefFactory = context
def receive = handleTimeouts orElse runRoute(demoRoute)
def handleTimeouts: Receive = {
case Timeout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Request timed out.")
}
}
// this trait defines our service behavior independently from the service actor
trait AccountService extends HttpService {
val demoRoute = {
get {
path("") {
respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here
complete(index)
}
} ~
path("ping") {
complete("PONG!")
} ~
path("timeout") { ctx =>
// we simply let the request drop to provoke a timeout
} ~
path("crash") { ctx =>
throw new RuntimeException("crash boom bang")
} ~
path("fail") {
failWith(new RuntimeException("aaaahhh"))
} ~
path("riaktestsetup") {
Test.setupTestData
complete("SETUP!")
} ~
path("riaktestfetch" / Rest) { id =>
complete(Test.read(id))
}
}
}
}
感谢您的帮助!
推荐答案
您可以使用 ~ 组合器组合来自不同控制器"的路由.
You can combine routes from different "Controllers" using ~ combinator.
class AccountServiceActor extends Actor with HttpService {
def actorRefFactory = context
def receive = handleTimeouts orElse runRoute(
new AccountService1.accountService1 ~ new AccountService2.accountService2)
def handleTimeouts: Receive = {
case Timeout(x: HttpRequest) =>
sender ! HttpResponse(StatusCodes.InternalServerError, "Request timed out.")
}
}
class AccountService1 extends HttpService {
val accountService1 = {
get {
path("") {
respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here
complete(index)
}
}
}
}
class AccountService2 extends HttpService {
val accountService2 = {
get {
path("someotherpath") {
respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here
complete(index)
}
}
}
}
这篇关于Spray.io 路由可以拆分成多个“控制器"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文