`
sillycat
  • 浏览: 2566875 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Spray(3)spray-routing

 
阅读更多
Spray(3)spray-routing


The spray-routing module provides a high-level, very flexible routing DSL for RESTful web services. Normally I will use it either on top of a spray-can HttpServer or inside of a servlet container together with spray-servlet.



Dependencies
spray-http, spray-httpx, spray-util, spray-caching, shapeless, Scalate, akka-actor



"io.spray"            %   "spray-routing"             % "1.1-M7",
"com.typesafe"        %   "config"                    % "1.0.0"


Configuration
Just like Akka spray-routing relies on the type safe config library for configuration. The same configuration file with akka, application.conf(reference.conf).



Getting Started
SimpleRoutingApp
package com.sillycat.easyspray.external

import spray.routing.SimpleRoutingApp

import spray.http.MediaTypes._

import scala.concurrent.duration._

object EasyRoutingApp extends App with SimpleRoutingApp {



  startServer(interface = "localhost", port = 8080) {

    get {

      path("") {

        redirect("/hello")

      } ~

      path("hello") {

        respondWithMediaType(`text/html`) { // XML is marshalled to `text/xml` by default, so we simply override here

          complete {

            <html>

              <h1>Say hello to <em>spray</em> on <em>spray-can</em>!</h1>

              <p>(<a href="/stop?method=post">stop server</a>)</p>

            </html>

          }

        }

      }

    } ~

    (post | parameter('method ! "post")) {

      path("stop") {

        complete {

          system.scheduler.scheduleOnce(1 second span) {

            system.shutdown()

          }

          "Shutting down in 1 second…"

        }

      }

    }

  }

 

}



Key Concepts
Big Picture
We have spray-can HttpServer and the spray-servlet connector servlet both an actor-level to response to incoming HTTP requests by simply replying with an HttpResponse.



We can do complete REST API by pattern-matching against the incoming HttpRequest. But it is not wise to do in that way.



As an alternative spray-routing provides a flexible DSL for expressing service behavior.



def receive = runRoute {

     path("ping"){

          get{

               complete("PONG")

          }

     }

}



Routes
type Route = RequestContext => Unit



Generally when a route receives a request (or rather a RequestContext for it) it can do one of the three things:

1. Complete the request by calling requestContext.complete(…)

2. Reject the request by calling requestContext.reject(…)

3. Ignore the request



Constructing Routes
ctx => ctx.complete("Response")     ----> complete("Response")



Composing Routes
Route transformation, Route filtering, Route chaining



The Routing Tree
varl route =

     a{

          b{

               c{…} ~

               d{…} ~

               ...

          } ~

          ...

     }



Directives
val route =
  path("order" / IntNumber) { id =>
    (get | put) { ctx =>
      ctx.complete("Received " + ctx.request.method + " request for order " + id)
    } }
Or

val getOrPut = get | put
val route =
  (path("order" / IntNumber) & getOrPut) { id => ctx =>
    ctx.complete("Received " + ctx.request.method + " request for order " + id) }


Rejections
The ~ operator was introduced, which connects two routes in a way that allows a second route to get a go at a request if the first route "rejected" it.



Exception Handling


import spray.routing.SimpleRoutingApp

import spray.http.MediaTypes._

import scala.concurrent.duration._

import spray.util.LoggingContext

import spray.routing.ExceptionHandler

import spray.util.LoggingContext

import spray.http.StatusCodes._

import spray.routing._



object EasyRoutingApp extends App with SimpleRoutingApp {



  implicit def myExceptionHandler(implicit log: LoggingContext) =

  ExceptionHandler.fromPF {

    case e: ArithmeticException => ctx =>

      log.warning("Request {} could not be handled normally", ctx.request)

      ctx.complete(InternalServerError, "Bad numbers, bad result!!!")

  }

…snip…


Timeout Handling
import spray.http._
import spray.routing._

class MyService extends Actor with HttpServiceActor {
  def receive = handleTimeouts orElse runRoute(myRoute)

  def myRoute: Route = `<my-route-definition>`

  def handleTimeouts: Receive = {
    case Timeout(x: HttpRequest) =>
      sender ! HttpResponse(StatusCodes.InternalServerError, "Too late")
  } }




References:
http://spray.io/documentation/spray-routing/

分享到:
评论

相关推荐

    spray-template

    使用spray-template时,开发者通常会将其与spray-routing结合,定义HTTP路由和对应的处理函数,这些函数负责填充模板并生成最终的响应。通过这种方式,spray-template可以帮助构建出结构清晰、易于维护的Web服务。 ...

    spray-swagger-sample:使用带有spray-swagger的spray的示例项目

    3. `build.sbt`: 使用 sbt(Scala Build Tool)定义项目的构建设置,包括依赖项管理。 4. `README.md`: 项目介绍和使用指南。 5. `.gitignore`: 文件忽略规则,用于 Git 版本控制。 **使用步骤** 要运行这个示例...

    scala-spray-demo

    二是spray-routing,提供了声明式路由构造器,使构建RESTful服务变得简单直观。在Scala-Spray-Demo中,Spray框架被用来构建RESTful API,允许开发者通过声明式的路由定义来处理HTTP请求。 **三、Swagger集成** ...

    Efficient Multiple-Copy Routing in Software-Defined Vehicular Networks

    3. 间歇连接网络(Intermittently Connected Networks,ICNs):这种网络是指网络中的节点(如车辆)只能断断续续地连接在一起,无法像传统网络那样维持稳定的连接状态。这种网络的一个重要特征是,数据包的传输需要...

    hecate-testing-1.0.24.zip

    3. **spray框架**:包括spray-can(HTTP服务器组件)、spray-routing(构建路由的DSL)、spray-client(HTTP客户端)等,它们共同为创建高效的HTTP服务提供了一整套解决方案。 4. **swagger规范**:Swagger定义了一...

    common-spray.scala:使用Spray的blinkbox书籍网络服务的通用代码

    核心组件包括路由(Routing)、喷射器(Sprayer)和响应处理器(ResponseBuilder)。路由负责处理HTTP请求,喷射器负责实际的网络通信,而响应处理器则将业务逻辑转化为HTTP响应。 在`common-spray.scala`项目中,...

    Routing_sensor_networks_ID.rar_wireless networks

    3. **数据聚合**:为了减少不必要的数据传输和能量消耗,路由协议常采用数据聚合技术,如GHT(Grid-based Hierarchical Clustering and Data Aggregation Technique),它在数据传输前进行数据融合,减少网络负载。...

    CCS-DTN: Clustering and Network Coding-Based Efficient Routing in Social DTNs

    综上所述,CCS-DTN(Clustering and Network Coding-Based Efficient Routing in Social DTNs)是结合了聚类技术和网络编码来提高社交DTN路由性能的方案。通过将移动节点进行聚类,并利用Spray and Wait方案进行簇内...

    DTN协议族源代码

    4. **Routing Protocol (RP)**:负责决定数据如何在DTN网络中传递,常见的路由策略有 Epidemic Routing、FIB-based Routing 和 Spray-and-Wait Routing 等。 5. **Bundle Storage and Forwarding (BSF)**:在没有...

    sbt.g8:我用作 Scala 项目起点的giter8 模板

    #Apply this templateg8 mhamrah/sbt #Also features a template for Spray-Routing appsg8 mhamrah/sbt -b spray#And for Spark Appsg8 mhamrah/sbt -b spark笔记Go风格的目录布局合并的 build.sbt 文件:包括 ...

    网络游戏-机会网络中的路由选择方法.zip

    - **Spray and Wait Routing**:这种方法首先将数据包均匀分配给遇到的几个节点,然后等待接收节点再转发给其他节点,以减少重复传输。 - **Delay-Tolerant Routing (DTN)**:DTN路由策略强调数据包的生命周期和...

    论文研究-基于机会网络有效数据预测转发路由算法.pdf

    在机会网络中,节点信息传输成功率和路由开销是衡量网络性能的主要指标,...通过仿真实验,并与机会网络中spray and wait和binary spray and wait比较,该算法提升了网络的平均传输成功率,减少了节点的平均路由开销。

    akka-http-master.rar

    3. **客户端**(Client Side):作为 HTTP 客户端,它可以发起 HTTP 请求,处理响应,并能与服务器建立持久连接,如 HTTP/2 的连接池。 4. **Marshallers 和 Unmarshallers**:它们负责将 Akka 的内部消息类型(如 ...

    CCS-DTN:基于聚类和网络编码的社交DTN中的高效路由

    针对现有研究中的一些缺陷,研究者提出了CCS-DTN(Clustering-based and Network Coding-enhanced Social DTN Routing)的新型解决方案,用以解决移动节点可以被分成不同簇的社交DTN中的路由问题。在该方案中,对于...

    无线传感网络路由算法模拟实现

    首先,无线传感网络的路由算法主要分为三类:数据为中心的路由(Data-Centric Routing)、位置为基础的路由(Location-Based Routing)和混合路由(Hybrid Routing)。数据为中心的路由如Spray and Focus或Gossiping...

    无线网络仿真软件使用.docx

    Direct Delivery是最基础的路由策略,直接将消息传递给目标节点,而其他如Flood、 Epidemic、Spray and Wait等策略则根据网络环境和性能需求提供不同选择。 总结来说,无线网络仿真软件ONE是一个功能丰富的工具,其...

Global site tag (gtag.js) - Google Analytics