我有一些现有的REST服务(下面的#1和#2)在不同的端点上运行,只用于内部。现在我想使用Spray将其中一些REST API(API-1和API-2)外部公开,因为该外部端点还将提供一些其他API(API-3,API-4)。
有没有一种简单/推荐的方法将外部REST请求转发到现有REST端点的新端点?
有没有一种简单/推荐的方法将外部REST请求转发到现有REST端点的新端点?
听起来你想要的是建议中的proxyTo
指令:
path("foo") {
get {
proxyTo("http://oldapi.example.com")
}
}
或者更可能的是proxyToUnmatchedPath
。这方面已经有一个问题被提出:
https://github.com/spray/spray/issues/145
看起来有人正在这方面努力;这是Spray分支中的提交记录:
https://github.com/bthuillier/spray/commit/d31fc1b5e1415e1b908fe7d1f01f364a727e2593
但是这个提交似乎还没有被合并到Spray主仓库中。您可以在问题页面上了解其状态。http://www.cakesolutions.net/teamblogs/http-proxy-with-spray
该页面的评论指出,Spray有一个名为ProxySettings
的未记录功能,并指向以下测试:
更新:Soumya已在spray-user Google Group上向Spray团队提出了这个问题:
https://groups.google.com/forum/#!topic/spray-user/MlUn-y4X8RE
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)
}