java - 在给定秒数后中断 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 状态代码。我将如何实现这一目标?
解决方案
您可以使用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
}
推荐阅读
- javascript - 使用 JS 槽 HTML 显示 Json
- wordpress - 覆盖 WooCommerce 过滤器中最低和最高价格的标准请求处理,以从自定义字段按价格获取产品
- java - 我的 Java 客户端没有读取整个 Socket 响应
- sapui5 - sapUI5 应用程序中的 Cloudinary SDK
- vb.net - How to Automatically Select a ListBox Item Based on the Current Month (VB.NET)
- c - 链接 .o 对象时,Makfile 会同时生成 `(.text+0x0): multiple definition` 和 `(.text+0x44): undefined reference to` 错误
- javascript - 无法在实时服务器上运行 Reactjs 代码
- java - 如何用另一个 java 对象的值更新一个 java 对象的所有字段?
- powershell - 如何在 powershell Pro Tools 中为 LogonName 组合 FirstName 和 LastName?
- html - 即使在 min-height:100% 处也没有填写 Div;