scala - 使用 futures 和 options 检查元素是否存在于数据库中并更新它

标签 scala redis future

我遇到的问题是我有元素存储在 Redis 中。我正在尝试更新可能不存在的元素上的计数器。

我有一个函数可以增加这些值,它的返回类型为

def increment(id: String): Future[Option[Long]]

因此,我调用电话查看该 id 是否存在。它的返回类型为 Future[Boolean]。如果这个 bool 值是 False 那么我想返回 None,并立即完成。但是,如果 bool 值为 True,那么我想再次调用来增加我的值,该值的返回类型为 Future[Long]。

这是我尝试过的一些代码:

for {
  exists <- redis.hExists(id, index) //returns Future[Boolean]
} yield if (exists) redis.hIncrBy(id, index, 1) //returns Future[Long]
  else None

现在我意识到这不起作用,但我不知道如何做到这一点。我可以将 None 包装在 Future 中,然后将整个事情压平,它应该给我一个 Future[Option[Long]],但我觉得必须有更好的方法来处理此类问题。

如果有人需要更多信息,我非常乐意澄清或解释我错过的任何内容。谢谢!

最佳答案

由于您在该链中的任何位置都没有真正的Option,因此您需要以某种方式插入它。将成功的 Future 映射到 Some 应该可以做到。

for {
    exists <- redis.hExists(id, index)
} yield {
   if (exists) redis.hIncrBy(id, index, 1).map(Some(_))
   else Future.successful(None)
}

关于scala - 使用 futures 和 options 检查元素是否存在于数据库中并更新它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27283914/

相关文章:

macos - 如何在Scala中读取网络流?

scala - spark cassandra 连接器和 SBT 的编译错误

scala - 为什么Spark with Play的 “NoClassDefFoundError: Could not initialize class org.apache.spark.SparkConf$”失败?

javascript - 在 express 路由器中使用 redis 客户端

Scala Multiple Future 包含在 Try 中

scala - 为什么在 ArrayBuffer 上调用 "tail"需要线性时间?

Redis Out of Memory 异常,但仍然有足够的内存

python - Redis 获取和设置装饰器

scala - 为什么我们需要 Future 和 Promise?

java - 为什么这个 Future 的方法阻塞了主线程?