Scala 欺骗快速启动客户端
我有一个简单的sbt项目,我在其中添加了Scala 欺骗快速启动客户端,scala,http,finagle,twitter-finagle,Scala,Http,Finagle,Twitter Finagle,我有一个简单的sbt项目,我在其中添加了“com.twitter”%%“finagle http”%%“6.33.0”。我正在遵循《推特骗局指南》。我的代码是直接复制粘贴: import com.twitter.finagle.{Http, Service} import com.twitter.finagle.http import com.twitter.util.{Await, Future} object Client extends App { val client: Servi
“com.twitter”%%“finagle http”%%“6.33.0”
。我正在遵循《推特骗局指南》。我的代码是直接复制粘贴:
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http
import com.twitter.util.{Await, Future}
object Client extends App {
val client: Service[http.Request, http.Response] = Http.newService("www.scala-lang.org:80")
val request = http.Request(http.Method.Get, "/")
request.host = "www.scala-lang.org"
val response: Future[http.Response] = client(request)
response.onSuccess { resp: http.Response =>
println("GET success: " + resp)
println(resp.contentString) // modification 1
}
Await.ready(response)
println("needed this") // modification 2
}
如果没有“modification 2
”,我将无法获得任何输出。添加了println
needed this
GET success: Response("HTTP/1.1 Status(200)")
Process finished with exit code 0
修改2
”的情况下打印响应modification 1
”中没有打印contentString
modification 1
”上设置断点,并使用当前状态评估resp.contentString
,则会根据需要返回网站的HTML
当程序正常运行时,我如何才能将其打印出来?Twitter的
Future
上的onSuccess
方法的签名与标准库的Future
上的签名不同-而不是:
def onSuccess[U](pf: PartialFunction[T, U])(implicit executor: ExecutionContext): Unit
你有这个:
def onSuccess(f: (A) ⇒ Unit): Future[A]
也就是说,它返回一个新的未来,该未来返回与旧未来相同的值,但也会产生副作用,而不仅仅是产生副作用。(作为旁注,在我看来,这是Twitter future API比标准库更好的许多方式之一——我更喜欢函数参数的返回类型是Unit
,而方法的返回类型不是)
在您的情况下,Finagle用于客户端的线程被后台监控,因此如果您没有明确等待未来的结果,就不能保证JVM不会在未来满足之前退出。更改代码以等待成功返回的未来结果将使一切按预期工作。谢谢Travis!我认为这是quickstart中的一个bug,所以很容易混淆。我会解决的。