4

我的代码调用服务器并获取old-response.

然后我想轮询,直到我从服务器(又名new-response)得到不同的响应。

II 使用 while 循环我可以new-response在轮询后保持并使用它。

如果我使用awaitility如何new-response轻松获得?

这是我的代码:

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);
        }
    };
}
4

2 回答 2

10

您可以使用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);
于 2020-07-07T11:31:30.157 回答
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,你也可以使用匿名内部类。

于 2016-09-11T11:19:54.130 回答