如何在awaitility回调中保留一个对象

时间:2016-09-11 08:32:27

标签: java multithreading polling awaitility

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

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

我使用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);
        }
    };
}

2 个答案:

答案 0 :(得分:1)

一种方法是制作一个记住它的专门的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,你也可以使用匿名内部类来完成它。

答案 1 :(得分:0)

您可以使用until(Callable callable, Predicate predicate)

例如:

Callable<MyObject> callable = queryForMyObject();
Predicate<MyObject> predicate = myObject -> myObject.getFooCount() > 3;

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

doStuff(myObject);