爲了提高我的Scala級別,我正在嘗試使用噴霧路由和彈性搜索(使用elastic4s)來編寫一點休息api。 這裏是我的路線定義:從Scala和Spray.io的Future onComplete case中返回一個字符串
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
)
}
}
}
}
這裏是我的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"
}
}
getFromElasticSearch封裝圖書館elastic4s調用的方法,通過我的特質得到。
trait elastic4s {
def get: Future[SearchResponse] = {
val client = ElasticClient.local
client execute { search in "ads"->"categories" }
}
這個庫通過方法client.execute
我希望我的方法getFromElasticSearch能夠適用一些修改searchResponse返回未來[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"
}
但我怎麼能發送「someOperations()」的輸出字符串的 我噴霧路由的路由聲明完整的方法是什麼? (而不是返回「{value:hey} \ n」) 這樣做的最佳方式是什麼?
我明白了,你的THX :) – ylos
你總是可以通過[阻塞吧](http://docs.scala-lang.org/overviews/core/futures.html)獲得未來的結果,但你不想這樣做。 – 4e6