如何跟踪未知数量的异步Web服务请求 [英] How to keep track of an unknown number of asynch web service requests

查看:75
本文介绍了如何跟踪未知数量的异步Web服务请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现以下情形:

我关注一个用户列表,并且每个人都关注其他用户列表(想想Twitter).我要执行以下操作:

I follow a list of users, and each of those people follow a list of other users (think Twitter). I want to do the following:

  • 给定一个特定的用户,得到该用户的所有关注对象
  • 从该x个人列表中,并行发出x请求以获取他们关注的人员列表
  • Given a particular user, get all the people that user follows
  • From that list of x people, make x requests in parallel to get the list of people that they follow

在游戏中,我想通过WS API来执行此操作,并且我猜想,当我并行发出x请求时,我将拥有x Future对象,这些对象代表每个调用的结果.我的问题是,如何确定所有期货何时完成?只要大多数请求成功返回,我可以接受一些失败的请求.一旦它们全部返回,我想对所有响应的汇总进行一些计算.

In Play, I want to do this via the WS API, and I am guessing that when I make the x requests in parallel, I will have x Future objects representing the result of each of those calls. My question is, how can I determine when all the Futures are complete? I am ok with a few requests failing, as long as the majority return successfully. Once they are all returned I want to do some computation on the aggregate of all the responses.

鉴于我不提前知道多少x,我如何确定所有期货何时完成?

How can I determine when all the Futures are complete, given that I don't know ahead of time how many x will be?

推荐答案

您可以使用flatMap编写期货,下面的示例使用一个URL数组发送多个请求以连接所有结果正文:

You can compose your futures using flatMap, the exemple below sends multiple request using an array of urls the concatenate all results body:

def compser = Action.async {
        val urls = List("http://jmaghreb.io","http://google.com","http://yahoo.fr","http://moroccojug.org")
        val futures:List[Future[WSResponse]] = urls.map(u=> WS.url(u).get())

        var f = futures.foldLeft[Future[String]](Future[String]{""})((e,c)=>{
          e.flatMap(oldRes => c.map(x=>oldRes+" ==> "+x.body))
        })

        f.map(s => Ok(s)).recover({case f=> Ok(s"Failure $f")})
      }

通过这种方式,您可以连接所有期货结果.

This way you can concatenate all your futures results.

如果您想忽略失败的请求,只需在flatMap内添加恢复,如下所示:

If you want to ignore failed request you can just add recover inside the flatMap as shown here:

var f = futures.foldLeft[Future[String]](Future[String]{""})((e,c)=>{
  e.flatMap(oldRes => {
    c.map(x=>oldRes+" ==> "+x.body).recover({case f=> oldRes })
  })
})

这篇关于如何跟踪未知数量的异步Web服务请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆