使用Scala和Spray.io从Future onComplete案例返回一个字符串

ylo*_*los 5 scala elasticsearch spray

我正在尝试使用喷射路由和弹性搜索(使用elastic4s)编写一个小的休息api,以提高我的scala级别.这是我的路线定义:

package com.example

import akka.actor.Actor
import spray.routing._
import com.example.core.control.CrudController

class ServiceActor extends Actor with Service {
  def actorRefFactory = context
  def receive = runRoute(routes)
}

trait Service extends HttpService {

  val crudController = new CrudController()
  val routes = {
      path("ads" / IntNumber) { id =>
      get {
          ctx =>
              ctx.complete(
                crudController.getFromElasticSearch
              )
      }
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的crudController:

class CrudController extends elastic4s
{

    def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => println(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
    }
}
Run Code Online (Sandbox Code Playgroud)

方法getFromElasticSearch通过我的trait get封装对库elastic4s的调用.

trait elastic4s {
    def get: Future[SearchResponse] = {
    val client = ElasticClient.local
    client execute { search in "ads"->"categories" }
    }
Run Code Online (Sandbox Code Playgroud)

该库通过client.execute方法返回Future [SearchResponse]对象

我希望我的方法getFromElasticSearch能够对searchResponse应用一些修改(如验证,序列化..),可能是这样的:

def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => someOperations(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "{value:hey} \n"
}

def someOperations(response: SearchResponse) : String = {
    println(" Doing some operations " + response)
    "result of operations"
}
Run Code Online (Sandbox Code Playgroud)

但是如何将"someOperations()"的输出字符串发送到我的喷涂路由路由声明的完整方法?(而不是返回"{value:嘿} \n")这是最好的方法吗?

4e6*_*4e6 0

喷雾有FutureMarshaller,这样就可以Future自行返回。

def getFromElasticSearch: Future[String] = {
  val result: Future[SearchResponse] = get
  result onFailure {
     case t: Throwable => println("An error has occured: " + t)
  }
  result.map(someOperation)
}
Run Code Online (Sandbox Code Playgroud)