Java 在给定的秒数后中断HTTP请求
我的API使用Java1.8、dropwizard 1.3.5和swagger拐点1.0.13 我有一个方法,它接受HTTP请求,延迟20秒,然后返回200状态码响应:Java 在给定的秒数后中断HTTP请求,java,swagger,Java,Swagger,我的API使用Java1.8、dropwizard 1.3.5和swagger拐点1.0.13 我有一个方法,它接受HTTP请求,延迟20秒,然后返回200状态码响应: public ResponseContext delayBy20Seconds(RequestContext context) { ResponseContext response = new ResponseContext().contentType(MediaType.APPLICATION_JSON_TYPE);
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状态代码。我将如何实现这一点 你可以使用谷歌番石榴库中的。这允许您将一个可调用对象包装到一个可以通过超时调用的操作中。如果可调用对象没有及时完成操作,它将抛出一个
TimeoutException
,您可以捕获该异常并返回400响应
例如:
TimeLimiter TimeLimiter=new SimpleTimeLimiter();
试一试{
字符串结果=timeLimiter.callWithTimeout(
()->dosomeHeavweightOperation(),15,时间单位为秒);
}捕获(超时异常e){
//返回400
}
一种不需要额外库的方法是使用java.util.concurrent
包。取消长时间运行的任务的最可靠的方法是在单独的线程中运行它
import java.util.concurrent.*;
...
private ExecutorService exec = Executors.newSingleThreadExecutor();
public ResponseContext delayBy20Seconds(RequestContext context) {
Callable<ResponseContext> task = new Callable<ResponseContext>() {
@Override
public ResponseContext call() throws Exception {
Thread.sleep(20000);
return new ResponseContext().contentType(MediaType.APPLICATION_JSON_TYPE);
}
};
List<Callable<ResponseContext>> tasks = new ArrayList<>();
tasks.add(task);
List<Future<ResponseContext>> done = exec.invokeAll(tasks, 15, TimeUnit.SECONDS);
Future<ResponseContext> task1 = done.get(0);
if (task1.isCancelled()) {
return some Error Response;
}
return task1.get();
}
import java.util.concurrent.*;
...
private ExecutorService exec=Executors.newSingleThreadExecutor();
公共响应文本延迟20秒(请求上下文){
可调用任务=新的可调用任务(){
@凌驾
public ResponseContext调用()引发异常{
睡眠(20000);
返回新的ResponseContext().contentType(MediaType.APPLICATION\u JSON\u TYPE);
}
};
列表任务=新建ArrayList();
任务。添加(任务);
List done=exec.invokeAll(任务,15,时间单位:秒);
未来任务1=完成。获取(0);
如果(task1.isCancelled()){
返回一些错误响应;
}
返回task1.get();
}
您的ExecutorService
不应该是静态的,因为您不想在线程之间为这个特定用途共享它
Callable
实现是完成长期运行任务的地方。在exec.invokeAll
调用中,我们会告诉它我们愿意等待多少。返回的未来列表将始终包含与任务列表一样多的元素,因此不需要检查它是否为空。我们只需要检查任务是否完成