您的位置:首页 > 其它

spray-routing使用Case Class Extraction

2015-09-10 13:48 232 查看
通过Case Class Extraction的方式我们也可以做到将请求参数包装成对象,也就是使用了Case Class Extraction抽取器,相当方便

构建route

val route2 = get{

path("color"){

parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color){ color =>
complete(color.toString)
}
}

}


这里有个优化的技巧,即route的构建过程与函数字面量的问题,

http://spray.io/documentation/1.2.3/spray-routing/advanced-topics/understanding-dsl-structure/

在编写route时注意该DSL规则就行了

还有就是IDEA是提示.as(Color)红色错误(不要理他,scala很"复杂",一些东西IDEA有时也无法探测到,例如implicit)

接着我们顺便编写检测器

case class Color(red:Int,green:Int,blue:Int){
require(red >=0&&green>=0&&blue>=0 && red<=255&&green<=255&&blue<=255)
}

这里我一次性把三个参数检测了,或者请自行选择

整个源码:

import akka.actor.{Props, ActorSystem}
import akka.io.IO
import akka.util.Timeout
import spray.can.Http
import spray.util.LoggingContext
import spray.httpx.encoding.Gzip
import spray.routing._
import spray.http._
import StatusCodes._
import scala.concurrent.duration._

object ActorTest4 extends App{
implicit val system = ActorSystem("mySystem")

val MyService = system.actorOf(Props[MyService])

implicit val timeout = Timeout(5.seconds)

IO(Http) ! Http.Bind(MyService,interface = "localhost",port=8080)

}
class MyService extends HttpServiceActor {

implicit val myRejectionHander = RejectionHandler{
case MissingCookieRejection(cookieName) :: _ =>
complete(BadRequest, "No cookies, no service!!!")
}
implicit  def myExceptionHander(implicit log:LoggingContext) = ExceptionHandler {
case e : ArithmeticException =>
requestUri { uri =>
log.warning("Request to {} could not be handled normally", uri)
complete(InternalServerError, "Bad numbers, bad result!!!")
}
}

def receive = runRoute(route2)

case class Color(red:Int,green:Int,blue:Int){
require(red >=0&&green>=0&&blue>=0 && red<=255&&green<=255&&blue<=255)
}

val route2 = get{

path("color"){

parameters('red.as[Int], 'green.as[Int], 'blue.as[Int]).as(Color){ color =>
complete(color.toString)
}
}

}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: