如何使用Spray.io构建RESTful API?

时间:2014-05-15 21:32:23

标签: scala rest spray spray-dsl

当我使用Spray.io开发RESTful API时,我应该如何构建我的应用程序?

我已经看过如何分割Spray应用程序的this answer,但我对此并不满意,因为它似乎没有使用“每个请求一个actor”的方法。我可以根据路径将根执行者的请求转发给我的应用程序中的其他actor,并在这些actor中定义相关的路由吗?

由于

2 个答案:

答案 0 :(得分:8)

您当然可以根据路径或其他任何方式将请求从一个actor转发到另一个actor。查看我的示例项目(它是示例项目的fork的分支):

https://github.com/gangstead/spray-moviedb/blob/master/src/main/scala/com/example/routes/ApiRouter.scala

来自接收所有请求的主actor的相关代码,并将它们路由到处理每个服务的其他actor:

  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)     
      }        
    }
  }  

答案 1 :(得分:0)

我在创建第一个完整的REST项目时遇到了很多困难。我发现的例子是世界级的......我读过很少的博客,很少有评论,我决定创建示例项目。它基于scala / akka / spray / mysql

完整的工作示例,使用websocket通知客户数据已更改等。您可以在https://github.com/vixxx123/scalasprayslickexample上查看

以下是该项目的路由示例代码:

val personCreateHandler = actorRefFactory.actorOf(RoundRobinPool(2).props(Props[CreateActor]), s"${TableName}CreateRouter")
val personPutHandler = actorRefFactory.actorOf(RoundRobinPool(5).props(Props[UpdateActor]), s"${TableName}PutRouter")
val personGetHandler = actorRefFactory.actorOf(RoundRobinPool(20).props(Props[GetActor]), s"${TableName}GetRouter")
val personDeleteHandler = actorRefFactory.actorOf(RoundRobinPool(2).props(Props[DeleteActor]), s"${TableName}DeleteRouter")

val userRoute =
    pathPrefix("person") {
        pathEnd {
            get {
                ctx => personGetHandler ! GetMessage(ctx, None)
            } ~
            post {
                entity(as[Person]) {
                    entity =>
                        ctx => personCreateHandler ! CreateMessage(ctx, entity)
                }
            }
        } ~
        pathPrefix (IntNumber){
            entityId => {
                pathEnd {
                    get {
                        ctx => personGetHandler ! GetMessage(ctx, Some(entityId))
                    } ~ put {
                        entity(as[Person]) { entity =>
                            ctx => personPutHandler ! PutMessage(ctx, entity.copy(id = Some(entityId)))
                        }
                    } ~ delete {
                        ctx => personDeleteHandler ! DeleteMessage(ctx, entityId)
                    } ~ patch {
                        ctx => personPutHandler ! PatchMessage(ctx, entityId)
                    }
                }
            }
        }
    }

来自create actor handler的样本:

override def receive: Receive = {

    case CreateMessage(ctx, person) =>

      val localCtx = ctx
      connectionPool withSession {
        implicit session =>
          try {
            val resId = PersonsIdReturning += person
            val addedPerson = person.copy(id = Some(resId.asInstanceOf[Int]))
            localCtx.complete(addedPerson)
            publishAll(CreatePublishMessage(TableName, localCtx.request.uri + "/" + addedPerson.id.get, addedPerson))
            L.debug(s"Person create success")
          } catch {
            case e: Exception =>
              L.error(s"Ups cannot create person: ${e.getMessage}", e)
              localCtx.complete(e)
          }
      }
  }

仍然缺少两个重要的事情:oauth2和通过websocket向特定用户/连接推送通知