一、前端访问后台接口设置超时时间
spring官方提供的配置:https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# SPRING MVC (WebMvcProperties)
spring.mvc.async.request-timeout= # Amount of time before asynchronous request handling times out.
也就是设置springmvc的超时时间:
1.在application.properties配置文件中配置该属性:超时时间看个人情况而定,单位毫秒。
2.controller中方法的返回值需是Callable<>类型。
@GetMapping("/test1")
public Callable<LcxJSONResult> test1() {
return () -> {
try {
// todo 这里模拟超时
TimeUnit.SECONDS.sleep(15);
} catch (InterruptedException | AsyncRequestTimeoutException e) {
e.printStackTrace();
System.out.println("超时");
return LcxJSONResult.errorException("超时");
}
System.out.println("SUCCESS");
return LcxJSONResult.ok("SUCCESS");
};
}
控制台打印:
注意:
超时报错后不会执行return方法,(是个疑惑点,还没有解决),所以无法正常给前端返回json。
解决办法:
springboor中配置全局异常拦截,就可以正常给前端返回了。
package com.leicx.weixin.exception;
import com.leicx.weixin.util.LcxJSONResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局异常信息捕捉(ajax请求)
* @author daxiong
* @date 2019-10-18 14:45
* @return
**/
@RestControllerAdvice
public class LcxAjaxExceptionHandler {
/**
* @author daxiong
* @date 2019-06-18 16:29
* @param request
* @param response
* @param e
* @return com.leicx.util.LcxJSONResult
**/
@ExceptionHandler(value = Exception.class)
public LcxJSONResult errorHandler(HttpServletRequest request,
HttpServletResponse response, Exception e) {
e.printStackTrace();
return LcxJSONResult.errorException(e.getMessage());
}
}
二、后台请求第三方接口设置超时时间
这里采用的是httpClient方法,在httpClient中设置请求超时时间。
注:这里结合了第一种情况超时的处理,如果不结合,可以不返回Callable类型
@GetMapping("/test1")
public Callable<LcxJSONResult> test1() {
return () -> {
try {
timeOut();
} catch (SocketTimeoutException | AsyncRequestTimeoutException e) {
e.printStackTrace();
System.out.println("超时");
return LcxJSONResult.errorException("超时");
}
System.out.println("SUCCESS");
return LcxJSONResult.ok("SUCCESS");
};
}
public void timeOut() throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 请求第三方接口
HttpGet httpGet = new HttpGet("http://localhost:8082/springboot/hello");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
// 使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
}
response.close();
httpClient.close();
}
请求接口,控制台打印:
返回给前端的数据:
三、Future类处理接口超时
可以参考我的另一篇博客:https://blog.csdn.net/llllllllll4er5ty/article/details/102588420
才疏学浅,难保万全。
如有问题,欢迎指正。