spray-routing使用Case Class Extraction

来源:互联网 发布:openresty是什么软件 编辑:程序博客网 时间:2024/05/21 18:41

通过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.IOimport akka.util.Timeoutimport spray.can.Httpimport spray.util.LoggingContextimport spray.httpx.encoding.Gzipimport 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)      }    }  }}


 


 

 

0 0
原创粉丝点击