Springboot设置服务超时配置方式
- 第一种方式 : application.yml or bootstarp.yml 设置 : spring.mvc.async.request-timeout=5000 单位: ms 超时时间 5s
- 第二种方式 : 重写WebMvcConfigurerAdapter 的configureAsyncSupport方法
@Configuration
public class WebMvcAdapter extends WebMvcConfigurationSupport {
@Override
public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(5000);
configurer.registerCallableInterceptors(timeoutInterceptor());
}
@Bean
public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
return new TimeoutCallableProcessingInterceptor();
}
}
- 第三种: 使用RestTemplate超时,设置配置HttpComponentsClientHttpRequestFactory中的RequestConfig属性
@Configuration
public class BeanConfig {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(5000);
requestFactory.setReadTimeout(1000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
return restTemplate;
}
}
- 测试结果 : 【需要配置生效,接口结果返回Callable类型】
1.
@GetMapping("/jk")
@ApiOperation("接口测试")
public Result jk() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
return Result.okWithMsg("测试接口触发操作");
}
测试没有效果的,超时没有作用到
返回结果 : {"code":0,"msg":"测试接口触发操作","data":null,"failed":false,"succeed":true}
2.
@GetMapping("/jk-Callable")
@ApiOperation("接口Callable测试")
public Callable<String> jkCallable() {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(10000); //this will cause a timeout
return "接口Callable测试";
}
};
}
测试是生效的,结论 : 需要配置生效,接口结果返回Callable类型
返回结果 : {"code":-1,"msg":"服务器异常","data":null,"failed":true,"succeed":false}
微服务接口超时配置
- 在微服务中,服务与服务调用是用feign调用,我们可以设置相应 ribbon 超时时间以熔断器抛异常接口信息,配置例如:
服务入口Nginx超时配置
- Nginx 设置接口请求超时
参考文章:
公众号
- 这个是我的公众号,可以关注下,一起学习,一起提升~