WebClient 超時(shí)后如何優(yōu)雅地處理異常
在使用 WebClient 時(shí),超時(shí)是一個(gè)常見(jiàn)的問(wèn)題。當(dāng)請(qǐng)求超時(shí)時(shí),WebClient 會(huì)拋出 TimeoutException。為了優(yōu)雅地處理這些異常,可以采用以下幾種方法:【起飛嘎嘎飛LSIXSO】
一、使用 onErrorResume
或 onErrorReturn
處理超時(shí)
onErrorResume 和 onErrorReturn 是 WebClient 提供的兩個(gè)操作符,用于在發(fā)生錯(cuò)誤時(shí)提供替代的響應(yīng)。
(一)onErrorResume
onErrorResume 允許你在發(fā)生錯(cuò)誤時(shí)返回一個(gè)替代的 Mono 或 Flux。
java復(fù)制
import org.springframework.web.reactive.function.client.WebClient;
import java.time.Duration;
public class WebClientTimeoutExample {
public static void main(String[] args) {
WebClient client = WebClient.builder()
.baseUrl("https://api.example.com")
.build();
client.get()
.uri("/data")
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5)) // 設(shè)置請(qǐng)求級(jí)超時(shí)為 5 秒
.onErrorResume(e -> Mono.just("Default response")) // 超時(shí)后返回默認(rèn)響應(yīng)
.subscribe(
response -> System.out.println("Response: " + response),
error -> System.err.println("Error: " + error.getMessage())
);
}
}
(二)onErrorReturn
onErrorReturn 允許你在發(fā)生錯(cuò)誤時(shí)返回一個(gè)特定的值。
java復(fù)制
client.get()
.uri("/data")
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5))
.onErrorReturn("Default response")
.subscribe(
response -> System.out.println("Response: " + response),
error -> System.err.println("Error: " + error.getMessage())
);
二、使用 retryWhen
實(shí)現(xiàn)重試機(jī)制
retryWhen 允許你定義一個(gè)重試策略,當(dāng)請(qǐng)求失敗時(shí)自動(dòng)重試。這可以提高系統(tǒng)的可靠性和容錯(cuò)能力。
java復(fù)制
import org.springframework.web.reactive.function.client.WebClient;
import java.time.Duration;
public class WebClientTimeoutExample {
public static void main(String[] args) {
WebClient client = WebClient.builder()
.baseUrl("https://api.example.com")
.build();
client.get()
.uri("/data")
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5)) // 設(shè)置請(qǐng)求級(jí)超時(shí)為 5 秒
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))) // 重試 3 次,每次間隔 2 秒
.subscribe(
response -> System.out.println("Response: " + response),
error -> System.err.println("Error: " + error.getMessage())
);
}
}
(一)自定義異常處理
你可以在 retryWhen 中定義更復(fù)雜的重試策略,例如在重試前執(zhí)行某些操作。
java復(fù)制
client.get()
.uri("/data")
.retrieve()
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5))
.retryWhen(Retry.backoff(3, Duration.ofSeconds(2))
.doBeforeRetry(retrySignal -> System.out.println("Retrying...")))
.subscribe(
response -> System.out.println("Response: " + response),
error -> System.err.println("Error: " + error.getMessage())
);
三、使用 onStatus
處理特定狀態(tài)碼
onStatus 允許你根據(jù) HTTP 狀態(tài)碼處理錯(cuò)誤。這可以用于處理 4xx 和 5xx 錯(cuò)誤。
java復(fù)制
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpStatus;
public class WebClientTimeoutExample {
public static void main(String[] args) {
WebClient client = WebClient.builder()
.baseUrl("https://api.example.com")
.build();
client.get()
.uri("/data")
.retrieve()
.onStatus(HttpStatus::is4xxClientError, response -> Mono.error(new RuntimeException("Client error")))
.onStatus(HttpStatus::is5xxServerError, response -> Mono.error(new RuntimeException("Server error")))
.bodyToMono(String.class)
.timeout(Duration.ofSeconds(5)) // 設(shè)置請(qǐng)求級(jí)超時(shí)為 5 秒
.subscribe(
response -> System.out.println("Response: " + response),
error -> System.err.println("Error: " + error.getMessage())
);
}
}
四、全局異常處理
你可以通過(guò)定義一個(gè)全局的異常處理邏輯來(lái)處理所有 WebClient 請(qǐng)求的異常。
java復(fù)制
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpStatus;
public class WebClientConfig {
public WebClient createWebClient() {
return WebClient.builder()
.filter(ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
if (clientResponse.statusCode().is4xxClientError()) {
return clientResponse.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new RuntimeException("Client error: " + errorBody)));
} else if (clientResponse.statusCode().is5xxServerError()) {
return clientResponse.bodyToMono(String.class)
.flatMap(errorBody -> Mono.error(new RuntimeException("Server error: " + errorBody)));
}
return Mono.just(clientResponse);
}))
.build();
}
}
五、總結(jié)
在使用 WebClient 時(shí),超時(shí)是一個(gè)常見(jiàn)的問(wèn)題。通過(guò)使用 onErrorResume、onErrorReturn、retryWhen 和 onStatus 等操作符,可以?xún)?yōu)雅地處理這些異常。這些方法不僅可以提高系統(tǒng)的可靠性,還可以提供更好的用戶(hù)體驗(yàn)。