缺少带有scala和spray路由的DefaultMarshallers
我是Scala新手,正在尝试编写一点RESTAPI 以下是我的路线定义:缺少带有scala和spray路由的DefaultMarshallers,scala,spray,Scala,Spray,我是Scala新手,正在尝试编写一点RESTAPI 以下是我的路线定义: 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 =
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需要一个隐式封送器来封送我未来的[String]对象。但我有点困惑,因为在文档中我们可以阅读
Scala编译器将为您的类型寻找范围内隐式封送拆收器,以完成将自定义对象转换为客户机接受的表示的工作。spray附带的以下封送器已在DefaultMarshallers特性源中定义为隐式对象
在我的情况下,所需的封送员属于DefaultMarshallers,我不必亲自暗示他。。我应该吗?当您使用未来的[T]值调用complete时,需要有一个隐式的ExecutionContext可用。顺便说一句,你通常不应该在Akka应用程序中依赖全局执行上下文。在参与者内部,您通常只需导入context.dispatcher,然后通过将签名更改为def getFromElasticSearch id:Integerimplicit ec:ExecutionContext:Future[String],将其作为隐式参数传递到CrudController。完美答案。谢谢jrudolph!: