java - 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.
解决方案
这与 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();
}
推荐阅读
- ag-grid - 如何使用单独的按钮在 ag 网格中展开 Master Detail?
- react-native - 在 iPhone X 上处理 ReactNative 中的 SafeArea
- python - 字符类在正则表达式中算作组吗?
- android - 单击子项中的按钮删除或删除可展开的列表视图项
- javascript - vue.js 不知道如何通过 props 将数据传递给另一个组件
- python-3.x - 如何用 Python 画图?
- amazon-dynamodb - 使用全局二级索引从 Dynamo DB 查询数据
- asp.net - 如何使用 asp.net Web Api 中的表单数据在 API 中对对象上传进行建模
- javascript - 为什么即使在反应中调用 e.nativeEvent.stopPropagation 后事件也会传播到父级?
- flutter - 如何在颤动的垂直列表视图中创建水平列表视图