首页 > 解决方案 > 在给定秒数后中断 HTTP 请求

问题描述

我为我的 API 使用 Java 1.8、dropwizard 1.3.5 和 swagger inflection 1.0.13。

我有一个接受 HTTP 请求的方法,延迟 20 秒,然后返回 200 状态代码响应:

public ResponseContext delayBy20Seconds(RequestContext context) {
    ResponseContext response = new ResponseContext().contentType(MediaType.APPLICATION_JSON_TYPE);

    Thread.sleep(20000);

    response.status(Response.Status.OK);
    return response;
}

如果操作(在这种情况下需要 20 秒)需要超过 15 秒,假设我想返回 400 状态代码。我将如何实现这一目标?

标签: javaswagger

解决方案


您可以使用Google Guava 库中的TimeLimiter之类的东西。这允许您将可调用对象包装在可以使用 Timeout 调用的操作中。如果 callable 没有及时完成操作,它会抛出一个TimeoutException你可以捕获的并返回 400 响应。

举个例子:

TimeLimiter timeLimiter = new SimpleTimeLimiter();
try {
  String result = timeLimiter.callWithTimeout(
                () -> doSomeHeavyWeightOperation(), 15, TimeUnit.SECONDS);
} catch (TimeoutException e) {
  // return 400
}

推荐阅读