我尝试使用喷涂路由和弹性搜索(使用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
)
}
}
}
}
这是我的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通过我的trait get封装对库elastic4s的调用。
trait elastic4s {
def get: Future[SearchResponse] = {
val client = ElasticClient.local
client execute { search in "ads"->"categories" }
}
该库通过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"
}
但是如何发送" someOperations()"的输出字符串?完整的方法 我的喷涂路线申报? (而不是返回" {值:嘿} \ n") 这样做的最佳方法是什么?
答案 0 :(得分:0)
Spray有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)
}
答案 1 :(得分:-2)
是否应该只遵循手册中显示的模式?
box-sizing