如何在awaitility回调中分开保存一个对象?

10

我的代码向服务器发送请求并获得一个旧响应

然后,我想要轮询直到从服务器获得不同的响应(即新响应)。

如果我使用while循环,我可以保存新响应并在轮询后使用它。

如果我使用awaitility,如何轻松地获取新响应

以下是我的代码:

public Version waitForNewConfig() throws Exception {
    Version oldVersion = deploymentClient.getCurrentConfigVersion(appName);
    await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(newVersionIsReady(oldVersion));
    Version newVersion = deploymentClient.getCurrentConfigVersion(appName);

}

private Callable<Boolean> newVersionIsReady(Version oldVersion) {
    return new Callable<Boolean>() {
        public Boolean call() throws Exception {
            Version newVersion = deploymentClient.getCurrentConfigVersion(appName);

            return !oldVersion.equals(newVersion);
        }
    };
}
2个回答

24
你可以使用ConditionFactory.until(Callable[T], Predicate[T])
例如:
Callable<MyObject> supplier = () -> queryForMyObject();
Predicate<MyObject> predicate = myObject -> myObject.getFooCount() > 3;

MyObject myObject = Awaitility.await()
   .atMost(1, TimeUnit.MINUTE)
   .pollInterval(Duration.ofSeconds(5))
   .until(supplier, predicate);

doStuff(myObject);

6

其中一种方法是创建一个专门的Callable实现,记住它:

public Version waitForNewConfig() throws Exception {
    NewVersionIsReady newVersionIsReady = new NewVersionIsReady(deploymentClient.getCurrentConfigVersion(appName));
    await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(newVersionIsReady);

    return newVersionIsReady.getNewVersion();
}

private final class NewVersionIsReady implements Callable<Boolean> {
    private final Version oldVersion;
    private Version newVersion;

    private NewVersionIsReady(Version oldVersion) {
        this.oldVersion = oldVersion;
    }

    public Boolean call() throws Exception {
        Version newVersion = deploymentClient.getCurrentConfigVersion(appName);

        return !oldVersion.equals(newVersion);
    }

    public Version getNewVersion() {
        return newVersion;
    }
}

另一种方法是将它存储在容器中(这里我使用数组作为示例)。
public Version waitForNewConfig() throws Exception {
    Version[] currentVersionHolder = new Version[1];
    Version oldVersion = deploymentClient.getCurrentConfigVersion(appName);
    await().atMost(1, MINUTES).pollInterval(5, SECONDS).until(() -> {
        Version newVersion = deploymentClient.getCurrentConfigVersion(appName);
        currentVersionHolder[0] = newVersion;
        return !oldVersion.equals(newVersion);
    });

    return currentVersionHolder[0];
}

如果您尚未使用Java 8,也可以使用匿名内部类来实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接