【问题标题】:Couchbase backoff with Java API使用 Java API 的 Couchbase 退避
【发布时间】:2014-04-10 13:58:19
【问题描述】:

我试图了解增量退避在 Java Couchbase API 中的工作原理。以下代码sn-p来自Couchbase Java Tutorial(我添加了几个cmets)。

public OperationFuture<Boolean> contSet(String key,
                                        int exp,
                                        Object value,
                                        int tries) {
  OperationFuture<Boolean> result = null;
  OperationStatus status;
  int backoffexp = 0;

  try {
    do {
      if (backoffexp > tries) {
        throw new RuntimeException("Could not perform a set after "
                + tries + " tries.");
      }
      result = cbc.set(key, exp, value);
      status = result.getStatus(); // Is this a blocking call?
      if (status.isSuccess()) {
        break;
      }
      if (backoffexp > 0) {
        double backoffMillis = Math.pow(2, backoffexp);
        backoffMillis = Math.min(1000, backoffMillis); // 1 sec max
        Thread.sleep((int) backoffMillis);
        System.err.println("Backing off, tries so far: " + backoffexp);
      }
      backoffexp++;

      // Why are we checking again if the operation previously failed
      if (!status.isSuccess()) {
        System.err.println("Failed with status: " + status.getMessage());
      }

    // If we break on success, why not do while(true)?
    } while (status.getMessage().equals("Temporary failure"));
  } catch (InterruptedException ex) {
    System.err.println("Interrupted while trying to set.  Exception:"
            + ex.getMessage());
  }

  if (result == null) {
    throw new RuntimeException("Could not carry out operation.");
  }

  return result;
}

是否仅在操作成功或失败时才返回对getStatus() 的调用? (即同步)。 Java Tutorial 似乎说它正在阻塞,但 Java API 说:

获取此操作的当前状态。请注意,操作状态可能会随着对 NodeLocator 指定的服务器的尝试和可能重试操作而改变。

为什么我们需要多次检查status.isSuccess()?如果它成功了,我们就会跳出循环,我们可以假设它失败了?

如果有任何理由做while (status.getMessage().equals("Temporary failure"))而不是while(true),因为我们在状态成功时调用break

谢谢

【问题讨论】:

    标签: java couchbase nosql


    【解决方案1】:

    getStatus() 强制Future 完成(即内部调用get(),因此可以知道操作的状态。换句话说,没有待处理在 APU 中的状态,所以你必须强制 Future 完成才能确定是状态。

    详见Operation_Future:getStatus的源码。

    【讨论】:

    • 谢谢。失败(即没有跳出循环),示例代码是否有充分的理由再次调用isSuccess()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2019-03-17
    • 1970-01-01
    • 2019-12-20
    • 2020-01-17
    • 2020-03-22
    相关资源
    最近更新 更多