gpt4 book ai didi

spring - 在@RestController 中限制时间执行的最佳方法

转载 作者:行者123 更新时间:2023-12-04 16:04:13 25 4
gpt4 key购买 nike

考虑以下代码:

@RestController
@RequestMapping("/timeout")
public class TestController {

@Autowired
private TestService service;

@GetMapping("/max10secs")
public String max10secs() {
//In some cases it can take more than 10 seconds
return service.call();
}
}

@Service
public class TestService {

public String call() {
//some business logic here
return response;
}
}

我想要完成的是,如果 TestService 中的方法 call 花费超过 10 秒,我想取消它并生成带有 的响应HttpStatus.REQUEST_TIMEOUT 代码。

最佳答案

我设法做到了,但我不知道是否有任何概念或实践缺陷是它遵循的......

一、spring-async的配置

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {

ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(10);
pool.setMaxPoolSize(10);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}

@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}
}

接下来, Controller 和服务修改:

@RestController
@RequestMapping("/timeout")
public class TestController {

@Autowired
private TestService service;

@GetMapping("/max10secs")
public String max10secs() throws InterruptedException, ExecutionException {
Future<String> futureResponse = service.call();
try {
//gives 10 seconds to finish the methods execution
return futureResponse.get(10, TimeUnit.SECONDS);
} catch (TimeoutException te) {
//in case it takes longer we cancel the request and check if the method is not done
if (futureResponse.cancel(true) || !futureResponse.isDone())
throw new TestTimeoutException();
else {
return futureResponse.get();
}
}
}
}

@Service
public class TestService {

@Async("threadPoolTaskExecutor")
public Future<String> call() {
try{
//some business logic here
return new AsyncResult<>(response);
} catch (Exception e) {
//some cancel/rollback logic when the request is cancelled
return null;
}
}
}

最后生成TestTimeoutException:

@ResponseStatus(value = HttpStatus.REQUEST_TIMEOUT, reason = "too much time")
public class TestTimeoutException extends RuntimeException{ }

关于spring - 在@RestController 中限制时间执行的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com