多个进程等待同一个 Future 完成(scala)

Multiple processes wait for the same Future to complete (scala)

我现在不能直接使用它,但这个问题突然出现在我的脑海中,在网上找不到好的答案:

我有一个函数 'callExactKeyFromDB' returns: Either[A, Future[A]](A= 来自本地内存缓存,Future[A] = 查询数据库)。我可以将该 Future 传递给不同的 threads/executions 上下文并让它们全部注册到 'onComplete' 还是每次调用此函数时我 return 一个新的未来更好,保留一个列表注册期货并尽快完成它们。

现在的问题是我可以用 1 个 Future 来做吗?我应该做吗?

(假设有 4 个进程从 DB 请求用户信息并正在等待它继续)

我会摆脱 Either[A,Future[A]] 并将其转换为 Future[A] 作为开始。

def getUserByKey(key:Int) : Future[User] =
  cache.users.contains(key) match {
    case true  => Future(cache.users(key))
    case false => Future(User(key = 101, name = "John Doe")) // db call
  }

这会让事情变得简单很多,我想...

如果 cache 在上下文之间共享,一旦保存,就不需要对数据库进行更多调用来获取该特定用户。

def saveUserCache(u:User) : Future[Unit] = Future{
  cache.users.contains(u.key) match {
    case true  => cache.users(u.key) = u
    case false => cache.users += (u.key -> u)
  }
}

然后可以混合这些期货创造其他期货

def renderUser(key:Int) : Future[String] =
  for {
    user   : User    <-  getUserByKey(key)
    update : Unit    <-  saveUserCache(user)
    output : String  <-  Future(s"${user.key}: ${user.name}")
  } yield output

这是否回答了您的问题?

是的,您可以使用单个 Future 注册多个回调。这需要更少的代码,更少的内存,并且更具可读性。