在Spray中将HTTP / REST请求转发到另一个REST服务器

时间:2015-01-17 00:13:25

标签: scala rest http akka spray

我在一些现有的REST服务(下面的#1和#2)上运行,这些服务仅在内部使用的不同端点上运行。现在我想使用Spray在外部公开一些REST API(API-1和API-2),因为这个外部端点还将提供一些额外的API(API-3,API-4)。

是否有一种简单/推荐的方法将外部REST请求转发到我的新端点到现有REST端点?

enter image description here

2 个答案:

答案 0 :(得分:4)

听起来你想要的是建议的proxyTo指令:

path("foo") {
  get {
    proxyTo("http://oldapi.example.com")
  }
}

(或者更可能是proxyToUnmatchedPath)。有一个问题可以解决:

https://github.com/spray/spray/issues/145

看起来有人一直在研究这个问题;这是Spray fork中的提交:

https://github.com/bthuillier/spray/commit/d31fc1b5e1415e1b908fe7d1f01f364a727e2593

但提交似乎尚未出现在主Spray回购中。您可以在问题页面询问其状态。

此外,这是CakeSolutions的博客文章,内容涉及如何手动执行代理:

http://www.cakesolutions.net/teamblogs/http-proxy-with-spray

该页面上的评论指出Spray有一个名为ProxySettings的未记录的东西,并指出以下测试:

https://github.com/spray/spray/blob/master/spray-can-tests/src/test/scala/spray/can/client/ProxySpec.scala

UPDATE; Soumya已经向Spray团队询问喷雾用户Google Group:

https://groups.google.com/forum/#!topic/spray-user/MlUn-y4X8RE

答案 1 :(得分:3)

我可以在CakeSolution blog的帮助下代理服务。在以下示例中,代理正在http://localhost:20000上运行,而实际的REST端点正在http://localhost:7001上运行。

不确定使用此方法的代理多服务。

我喜欢@cmbaxter使用Nginx作为代理的解决方案,但我仍然很好奇是否有办法扩展以下方法在Spray中执行此操作。

import akka.actor.{ActorRef, Props}
import akka.io.IO
import akka.util.Timeout
import spray.can.Http
import spray.can.Http.ClientConnectionType
import spray.http.HttpResponse
import spray.routing.{RequestContext, HttpServiceActor, Route}


import scala.concurrent.duration._
import akka.pattern.ask


object ProxyRESTService {

   def main(args: Array[String]) {

   //create an actor system
   implicit val actorSystem = akka.actor.ActorSystem("proxy-actor-system")
   implicit val timeout: Timeout = Timeout(5 seconds)
   implicit val dis = actorSystem.dispatcher

   //host on which proxy is running
   val proxyHost = "localhost"
   //port on which proxy is listening
   val proxyPort = 20000

  //host where REST service is running
  val restServiceHost = "localhost"
  //port where REST service is running
  val restServicePort = 7001

  val setup = Http.HostConnectorSetup(
   proxyHost,
   proxyPort,
   connectionType = ClientConnectionType.Proxied(restServiceHost,   restServicePort)
)

IO(Http)(actorSystem).ask(setup).map {
  case Http.HostConnectorInfo(connector, _) =>
    val service = actorSystem.actorOf(Props(new ProxyService(connector)))
    IO(Http) ! Http.Bind(service, proxyHost, port = proxyPort)
}
}

}

class ProxyService(connector: ActorRef) extends HttpServiceActor  {
  implicit val timeout: Timeout = Timeout(5 seconds)
  implicit def executionContext = actorRefFactory.dispatcher
  val route: Route = (ctx: RequestContext) => ctx.complete(connector.ask(ctx.request).mapTo[HttpResponse])
  def receive: Receive = runRoute(route)
}