2017-07-28 227 views
0

爲了減少項目中第三方依賴項的數量,我正在使用scalaj改寫scalaj中的一些應用層代碼(我們已經在其他項目中使用akka) )代碼只是簡單地將常見類型的請求包裝到由庫提供的基本一般請求中通過代理路由akka-http請求

大多數情況下它一直很好,但我堅持在可選地向請求添加代理的問題上。

請求應直接傳送到目的地或通過代理服務器,由運行時的參數確定。

在我scalaj實現,我下面的輔助類和方法

object HttpUtils { 
    private def request(
       host: Host, 
       method: HttpMethod, 
       params: Map[String, String], 
       postData: Option[String], 
       timeout: Duration, 
       headers: Seq[(String, String)], 
       proxy: Option[ProxyConfig] 
      ): HttpResponse[String] = { 
    // most general request builder. Other methods in the object fill in parameters and wrap this in a Future 
    val baseRequest = Http(host.url) 
    val proxiedRequest = addProxy(proxy, baseRequest) 
    val fullRequest = addPostData(postData)(proxiedRequest) 
     .method(method.toString) 
     .params(params) 
     .headers(headers) 
     .option(HttpOptions.connTimeout(timeout.toMillis.toInt)) 
     .option(HttpOptions.readTimeout(timeout.toMillis.toInt)) 
    fullRequest.asString // scalaj for send off request and block until response 
    } 

     // Other methods ... 

    private def addProxy(proxy: Option[ProxyConfig], request: HttpRequest): HttpRequest = 
    proxy.fold(request)((p: ProxyConfig) => request.proxy(p.host, p.port)) 
} 

case class ProxyConfig(host: String, port: Int) 

有沒有建立與阿卡-HTTP類似結構的方法嗎?

回答

1

Akka HTTP確實有proxy support,從版本10.0.9開始,它仍然不穩定。請記住API可能會發生變化,您可以執行類似以下操作來處理可選代理設置:

import java.net.InetSocketAddress 

import akka.actor.ActorSystem 
import akka.stream.ActorMaterializer 
import akka.http.scaladsl.{ClientTransport, Http} 

implicit val system = ActorSystem() 
implicit val materializer = ActorMaterializer() 

case class ProxyConfig(host: String, port: Int) 

val proxyConfig = Option(ProxyConfig("localhost", 8888)) 
val clientTransport = 
    proxyConfig.map(p => ClientTransport.httpsProxy(InetSocketAddress.createUnresolved(p.host, p.port))) 
      .getOrElse(ClientTransport.TCP) 

val settings = ConnectionPoolSettings(system).withTransport(clientTransport) 
Http().singleRequest(HttpRequest(uri = "https://google.com"), settings = settings)