我正在尝试将AsyncHttpClient和Scalaz任务组合在一起。通常,如果我使用AsyncHttpClient,我可以调用client.close来停止客户机。
val asyncHttpClient = new AsyncHttpClient()
println(asyncHttpClient.prepareGet("http://www.google.com"))
asyncHttpClient.close()所以电流就会停止。但是,如果我将api调用包装到任务中。我不知道怎么阻止它。
def get(s: String) = Task.async[Int](k => {
asyncHttpClient.prepareGet(s).execute(toHandler)
Thread.sleep(5000)
asyncHttpClient.closeAsynchronously()
} )
def toHandler[A] = new AsyncCompletionHandler[Response] {
def onCompleted(r: Response) = {
println("get response ", r.getResponseBody)
r
}
def onError(e: Throwable) = {
println("some error")
e
}
}
println(get("http://www.google.com").run)当前进程仍在运行。我认为原因是任务和AsynClient都是异步的。我不知道该怎么办才能关闭它
事先非常感谢
发布于 2016-02-24 03:08:34
问题是Task.async接受一个可以注册回调的函数。这有点让人困惑,而且类型没有多大帮助,因为里面有那么多该死的Unit,但是这里的意思是,您需要更多这样的东西:
import com.ning.http.client._
import scalaz.syntax.either._
import scalaz.concurrent.Task
val asyncHttpClient = new AsyncHttpClient()
def get(s: String): Task[Response] = Task.async[Response](callback =>
asyncHttpClient.prepareGet(s).execute(
new AsyncCompletionHandler[Unit] {
def onCompleted(r: Response): Unit = callback(r.right)
def onError(e: Throwable): Unit = callback(e.left)
}
)
)这并不能处理关闭客户端的问题--它只是为了展示一般的想法。您可以在处理程序中关闭客户端,但我建议如下所示:
import com.ning.http.client._
import scalaz.syntax.either._
import scalaz.concurrent.Task
def get(client: AsyncHttpClient)(s: String): Task[Response] =
Task.async[Response](callback =>
client.prepareGet(s).execute(
new AsyncCompletionHandler[Unit] {
def onCompleted(r: Response): Unit = callback(r.right)
def onError(e: Throwable): Unit = callback(e.left)
}
)
)
def initClient: Task[AsyncHttpClient] = Task(new AsyncHttpClient())
def closeClient(client: AsyncHttpClient): Task[Unit] = Task(client.close())然后:
val res = for {
c <- initClient
r <- get(c)("http://www.google.com")
_ <- closeClient(c)
} yield r
res.unsafePerformAsync(
_.fold(
_ => println("some error"),
r => println("get response " + r.getResponseBody)
)
)这避免了closeAsynchronously (无论如何,它似乎是going away )。
https://stackoverflow.com/questions/35590978
复制相似问题