【问题标题】:scala - dispatch example not workingscala - 调度示例不起作用
【发布时间】:2013-02-07 11:13:01
【问题描述】:

我正在关注dispatchdocs 中的第一个示例 -

    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    for (c <- country)
      println(c)

我没有打印任何输出。当我将其更改为以下以进行阻塞调用时,我会得到输出。

val res = country()
println(res)

需要帮助。

完整程序-

import dispatch._
object DispatchTest {

  def main(args: Array[String]) {
    val svc = url("http://api.hostip.info/country.php")
    val country = Http(svc OK as.String)
    for (c <- country)
      println(c)
  }
}

【问题讨论】:

  • 我不认为是阻塞.. res 仍然是 Future 不是吗?试试 println(res.get)
  • 对我来说它按原样完美运行......而且它应该,因为for 理解将println 命令包装在Promise 对象中,所以它只会在@ 987654329@值可用
  • 您使用的是什么版本的调度?你能展示你的 build.sbt 吗?
  • 无论如何,在我看来,这个问题更适合dispatch mailing list
  • 将上面的 build.sbt 粘贴到问题中。

标签: scala scala-dispatch


【解决方案1】:

嗯,这里不确定,但可能问题是您的主线程完成得太快,后台线程(其中 Dispatch 异步工作)没有时间采取行动?

要检查这一点,您可以尝试插入延迟:

for (c <- country) // Here we spawn a background thread!
  println(c)

Thread.sleep(500) // So let's wait half a second for it to work

当然,在实际程序中,您永远不需要这样做。

延迟的另一种选择是在 main 末尾添加 readLine()

【讨论】:

  • 您还可以在将代码粘贴到 sbt-console 时检查您的代码是否有效
  • 是的,就是这样。当我添加延迟时,我得到了输出。谢谢!
  • 您可能需要增加延迟,以防连接速度非常慢。
【解决方案2】:

在这里工作:

scala> import dispatch._
import dispatch._

scala> val svc = url("http://api.hostip.info/country.php")
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
svc: com.ning.http.client.RequestBuilder = com.ning.http.client.RequestBuilder@2f823290

scala> val country = Http(svc OK as.String)
country: dispatch.Promise[String] = Promise(-incomplete-)

scala> for (c <- country)
     |   println(c)

scala> BR

注意BR 出现在提示符之后。

您确定该国家/地区没有印在某处,但您没有注意到是因为它与其他输出混淆了吗?

【讨论】:

  • 我将它作为主要功能运行。我已经更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2017-03-21
  • 2012-07-05
相关资源
最近更新 更多