五種實(shí)現(xiàn)方式配置Spring Boot API接口超時(shí)時(shí)間
環(huán)境:SpringBoot3.4.0
1. 簡(jiǎn)介
在開發(fā)API接口時(shí),配置API接口的超時(shí)時(shí)間是一項(xiàng)非常重要的任務(wù)。超時(shí)時(shí)間的設(shè)置對(duì)于確保系統(tǒng)的穩(wěn)定性和響應(yīng)性至關(guān)重要。當(dāng)客戶端發(fā)送請(qǐng)求到服務(wù)器時(shí),如果服務(wù)器由于某些原因(如數(shù)據(jù)庫(kù)查詢緩慢、外部服務(wù)調(diào)用失敗等)無法及時(shí)響應(yīng),那么設(shè)置合理的超時(shí)時(shí)間可以防止服務(wù)器資源被長(zhǎng)時(shí)間占用,從而避免系統(tǒng)崩潰或性能下降。
在Spring Boot中,有多種方式可以配置API接口的超時(shí)時(shí)間。針對(duì)不同的應(yīng)用場(chǎng)景,選擇正確的配置方式,可以確保系統(tǒng)在面對(duì)各種復(fù)雜場(chǎng)景時(shí)都能保持高效和穩(wěn)定。
本篇文章將通過的介紹如下幾種API超時(shí)情況的配置:
- 事務(wù)超時(shí)時(shí)間配置
如果你的當(dāng)前的API接口涉及到事務(wù)相關(guān),那么我們可以通過設(shè)置設(shè)置的超時(shí)時(shí)間來確保由于數(shù)據(jù)庫(kù)緩慢要引起的超時(shí)情況。 - 基于Resilience4j的超時(shí)保護(hù)機(jī)制
我們可以通過Resilience4j提供的超時(shí)機(jī)制來設(shè)置有效的超時(shí)時(shí)間。 - 異步請(qǐng)求超時(shí)
如果你當(dāng)前請(qǐng)求是異步請(qǐng)求,那么我們可以通過配置異步超時(shí)時(shí)間來限制接口等待時(shí)間。 - HTTP Client超時(shí)配置
我們將介紹3種HTTP Client超時(shí)的配置,分別是RestTemplate,RestClient,WebClient。 - 基于NGINX代理超時(shí)配置
通常我們的后端接口一般會(huì)通過NGINX進(jìn)行反向代理,在這種情況下,我們可以在其代理上配置超時(shí)時(shí)間。
2. 實(shí)戰(zhàn)案例
2.1 事務(wù)超時(shí)配置
我們可以在數(shù)據(jù)庫(kù)調(diào)用中實(shí)現(xiàn)請(qǐng)求超時(shí)的一種方法是利用Spring的@Transactional注解。該注解具有一個(gè)可以設(shè)置的超時(shí)屬性。該屬性的默認(rèn)值為-1,相當(dāng)于沒有設(shè)置任何超時(shí)。
@Transactional(timeout = 1)
public List<User> query() {
this.userRepository.findById(8L).ifPresent(System.out::println) ;
try {
TimeUnit.SECONDS.sleep(1) ;
} catch (InterruptedException e) {}
return this.userRepository.findAll() ;
}
如上配置注解中配置超時(shí)時(shí)間為1s,內(nèi)部執(zhí)行時(shí)先根據(jù)id查詢,此時(shí)能正常執(zhí)行,當(dāng)休眠1s后,再次執(zhí)行數(shù)據(jù)庫(kù)操作將拋出超時(shí)異常。
首先,我們進(jìn)行如下異常配置:
@ExceptionHandler(TransactionTimedOutException.class)
public ResponseEntity<Object> txTimeout(TransactionTimedOutException ex) {
return ResponseEntity.ok("請(qǐng)求超時(shí): " + ex.getMessage()) ;
}
測(cè)試接口
@GetMapping
public ResponseEntity<Object> query() {
return ResponseEntity.ok(this.userService.query()) ;
}
測(cè)試結(jié)果
圖片
以上我們利用了事務(wù)的超時(shí)時(shí)間來保護(hù)接口。
2.2 基于Resilience4j的超時(shí)保護(hù)機(jī)制
Resilience4j提供了一個(gè)TimeLimiter模塊,專門用來處理超時(shí)保護(hù)的。
首先,引入下面依賴:
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version>
</dependency>
接下來,通過注解配置需要保護(hù)的接口
@TimeLimiter(name = "queryUser", fallbackMethod = "fallbackQuery")
@GetMapping
public CompletionStage<ResponseEntity<Object>> query() {
return CompletableFuture.supplyAsync(() -> {
try {
// 模擬耗時(shí)操作
TimeUnit.SECONDS.sleep(2) ;
} catch (InterruptedException e) {}
return ResponseEntity.ok("success") ;
}) ;
}
public CompletionStage<ResponseEntity<Object>> fallbackQuery(Throwable e) {
return CompletableFuture.completedStage(ResponseEntity.ok(e.getMessage())) ;
}
說明:
name:在配置文件中定義的超時(shí)相關(guān)配置,如果配置文件中沒有配置則使用默認(rèn)的配置。
fallbackMethod:當(dāng)發(fā)生超時(shí)現(xiàn)象將調(diào)用的降級(jí)方法。
注意:方法的返回值必須是CompletionStage類型。
最后,配置超時(shí)
resilience4j:
timelimiter:
instances:
#該名稱為上面注解中的name
queryUser:
timeout-duration: 1s
測(cè)試結(jié)果
圖片
此種方式是不是非常的簡(jiǎn)單好用,一個(gè)注解搞定。
2.3 異步請(qǐng)求超時(shí)配置
當(dāng)我們的API接口是異步請(qǐng)求時(shí),我們可以直接在配置文件中對(duì)異步請(qǐng)求的超時(shí)時(shí)間進(jìn)行配置:
spring:
mvc:
async:
request-timeout: 1s
異步請(qǐng)求接口
@GetMapping("/async")
public Callable<String> async() {
return () -> {
try {
TimeUnit.SECONDS.sleep(10) ;
} catch (InterruptedException e) {
return "任務(wù)中斷 - " + e.getMessage() ;
}
return "異步請(qǐng)求成功" ;
} ;
}
測(cè)試結(jié)果
圖片
雖然這里休眠了10s,但在1s后,直接輸出了異常信息。
2.4 HTTP Client超時(shí)配置
這里我們將介紹3種接口調(diào)用的超時(shí)配置,分別是:RestTemplate,RestClient已經(jīng)WebClient,其中RestTemplate與RestClient是基于阻塞式調(diào)用并且RestClient是Spring6.1版本開始提供的;而WebClient則是基于響應(yīng)式的調(diào)用(非阻塞)。官方推薦使用WebClient。
RestTemplate超時(shí)配置
@Bean
RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
// 連接超時(shí)配置
.connectTimeout(Duration.ofSeconds(1))
// 讀取超時(shí)配置
.readTimeout(Duration.ofSeconds(1))
.build() ;
}
這是最簡(jiǎn)單的配置,你還可以通過如下工廠方式配置
@Bean
RestTemplate restTemplate() {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
.withConnectTimeout(Duration.ofSeconds(1))
.withReadTimeout(Duration.ofSeconds(1));
RestTemplate restTemplate = new RestTemplate(
ClientHttpRequestFactoryBuilder.detect().build(settings)) ;
return restTemplate ;
}
根據(jù)你的環(huán)境選擇不同的方式進(jìn)行配置。
RestClient超時(shí)配置
RestClient的配置方式與上面的RestTemplate差不多。
@Bean
RestClient restClient() {
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.defaults()
.withConnectTimeout(Duration.ofSeconds(1))
.withReadTimeout(Duration.ofSeconds(1)) ;
return RestClient
.builder()
.requestFactory(ClientHttpRequestFactoryBuilder.detect().build(settings))
.build() ;
}
最后,我們?cè)賮斫榻B官方推薦的WebClient。
WebClient超時(shí)配置
首先,我們要引入以下的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
下面進(jìn)行超時(shí)配置:
@Bean
WebClient webClient() {
HttpClient httpClient = HttpClient.create()
.doOnConnected(conn -> conn
.addHandlerLast(new ReadTimeoutHandler(1))
.addHandlerLast(new WriteTimeoutHandler(1))) ;
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient ))
.build() ;
}
下面我們通過WebClient進(jìn)行接口調(diào)用進(jìn)行測(cè)試
訪問接口
@GetMapping("/client")
public String client() {
try {
TimeUnit.SECONDS.sleep(3) ;
} catch (InterruptedException e) {
return "任務(wù)中斷 - " + e.getMessage() ;
}
return "success" ;
}
通過WebClient訪問該接口:
private final WebClient webClient ;
this.webClient
.get()
.uri("http://localhost:8080/api/users/client")
.retrieve()
.bodyToMono(String.class)
// 當(dāng)發(fā)生錯(cuò)誤時(shí)會(huì)自動(dòng)調(diào)用該方法進(jìn)行恢復(fù)繼續(xù)執(zhí)行
.onErrorResume(ex -> {
return Mono.just("發(fā)生錯(cuò)誤: " + ex.getMessage()) ;
})
.subscribe(System.out::println) ;
測(cè)試結(jié)果:
io.netty.handler.timeout.ReadTimeoutException: null
發(fā)生錯(cuò)誤: null
以上就是關(guān)于HTTP Client的超時(shí)配置。
2.5 基于NGINX代理超時(shí)配置
通過NGINX反向代理配置超時(shí)時(shí)間
location / {
proxy_pass http://127.0.0.1:8080;
proxy_connect_timeout 1s; # 連接超時(shí)時(shí)間為30秒
proxy_send_timeout 1s; # 發(fā)送請(qǐng)求超時(shí)時(shí)間為60秒
proxy_read_timeout 1s; # 讀取響應(yīng)超時(shí)時(shí)間為60秒
}
當(dāng)發(fā)生超時(shí)時(shí),我們這里通過日志查看:
[error] 11172#27080: *1 upstream timed out
(10060: A connection attempt failed because the connected
party did not properly respond after a period of time,
or established connection failed because connected
host has failed to respond) while reading
response header from upstream,
client: 127.0.0.1, server: localhost,
request: "GET /api/users/client HTTP/1.1",
upstream: "http://127.0.0.1:8080/api/users/client",
host: "localhost:1080"
當(dāng)發(fā)生異常,我們還可以進(jìn)行如下的配置,進(jìn)行友好提示:
location / {
proxy_pass http://127.0.0.1:8080;
proxy_connect_timeout 1s; # 連接超時(shí)時(shí)間為30秒
proxy_send_timeout 1s; # 發(fā)送請(qǐng)求超時(shí)時(shí)間為60秒
proxy_read_timeout 1s; # 讀取響應(yīng)超時(shí)時(shí)間為60秒
# 指定自定義錯(cuò)誤頁(yè)面
error_page 504 /timeout.html;
# 指定自定義錯(cuò)誤頁(yè)面的位置
location = /timeout.html {
root D:/all/html/;
internal;
}
}
圖片