一、前端訪問後臺接口設置超時時間
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
才疏學淺,難保萬全。
如有問題,歡迎指正。