首页 > 解决方案 > after a interval send different response from a rest endpoint url

问题描述

There is one application which use to keep on polling some rest endpoint URL to get status after a specific interval. The rest API is waiting for some action to get complete. Till the time action won't get complete and application will hit the endpoint, this rest API send status as status in response as 'in progress'. once action will get complete rest API sends success as status in response.

I have challenge to mock this rest API as don't want to hit actual rest API for testing.

Is there any way to send different response from mock rest API after a interval when application will poll by hitting the endpoint?

I am using vertx with java for this.

标签: javarestvert.x

解决方案


这与 Vert.x 没有特别的关系,但仍然如此。

这里的技巧不是计算间隔,而是这个模拟端点被命中的次数。

这是一个代码来演示它应该如何工作:

private static final Vertx vertx = Vertx.vertx();
private static final HttpClient client = vertx.createHttpClient(
        new HttpClientOptions()
                .setDefaultHost("localhost")
                .setDefaultPort(8443));
public static void main(final String[] args) {
    AtomicInteger hitCounter = new AtomicInteger(0);
    vertx.createHttpServer().requestHandler((c) -> {
        if (hitCounter.incrementAndGet() >= 5) {
            c.response().setStatusCode(200).end();
        }
        else {
            c.response().setStatusCode(202).end();
        }
    }).listen(8443);

    System.out.println("Server started");

    callServerUntilSuccess();
}

public static void callServerUntilSuccess() {
    client.request(HttpMethod.GET, "/", (r) -> {
        if (r.statusCode() == 200) {
            System.out.println("I'm done");
        }
        else {
            System.out.println("I'll try again");
            vertx.setTimer(1000, (l) -> callServerUntilSuccess());
        }
    }).end();
}

推荐阅读