我是Scala的新手,并尝试编写一些REST API。
这是我的路线定义:
package com.example
import akka.actor.Actor
import com.example.core.control.CrudController
import spray.routing._
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 {
complete(
crudController.getFromElasticSearch(id)
)
}
}
}
}
这是我的控制器
package com.example.core.control
import com.example._
import org.elasticsearch.action.search.SearchResponse
import scala.concurrent._
import ExecutionContext.Implicits.global
class CrudController extends elastic4s
{
def getFromElasticSearch (id:Integer) : Future[String] = {
val result: Future[SearchResponse] = get
result onFailure {
case t: Throwable => println("An error has occured: " + t)
}
result map { response =>
response.toString
}
}
}
当我尝试运行此代码时,我遇到以下异常:
Error:(22, 58) could not find implicit value for parameter marshaller: spray.httpx.marshalling.ToResponseMarshaller[scala.concurrent.Future[String]]
crudController.getFromElasticSearch(id)
我非常理解这个错误,spray需要一个隐式编组器才能编组我的Future [String]对象。但我有点困惑,因为在文档中我们可以阅读
Scala编译器将为您的类型查找范围内的隐式Marshaller,以完成将自定义对象转换为客户端接受的表示的工作。 spray附带已经定义的以下marshallers(作为DefaultMarshallers特性中的隐式对象)Source https://github.com/spray/spray/wiki/Marshalling-and-Unmarshalling
在我的情况下,所需的封送者属于DefaultMarshallers,我不应该自己隐瞒他。我应该吗?