对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cn

过滤器

您可以通过 注册客户端过滤器 () 以拦截和修改请求,如下例所示:ExchangeFilterFunctionWebClient.Builderspring-doc.cn

WebClient client = WebClient.builder()
		.filter((request, next) -> {

			ClientRequest filtered = ClientRequest.from(request)
					.header("foo", "bar")
					.build();

			return next.exchange(filtered);
		})
		.build();
val client = WebClient.builder()
		.filter { request, next ->

			val filtered = ClientRequest.from(request)
					.header("foo", "bar")
					.build()

			next.exchange(filtered)
		}
		.build()

这可用于横切关注点,例如身份验证。以下示例使用 通过静态工厂方法进行基本身份验证的过滤器:spring-doc.cn

import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = WebClient.builder()
		.filter(basicAuthentication("user", "password"))
		.build();
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication

val client = WebClient.builder()
		.filter(basicAuthentication("user", "password"))
		.build()

可以通过更改现有实例来添加或删除过滤器,从而 在不影响原始实例的新实例中。例如:WebClientWebClientspring-doc.cn

import static org.springframework.web.reactive.function.client.ExchangeFilterFunctions.basicAuthentication;

WebClient client = webClient.mutate()
		.filters(filterList -> {
			filterList.add(0, basicAuthentication("user", "password"));
		})
		.build();
val client = webClient.mutate()
		.filters { it.add(0, basicAuthentication("user", "password")) }
		.build()

WebClient是围绕过滤器链的薄立面,后跟 .它提供了一个工作流来发出请求、编码到更高级别或从更高级别编码 level 对象,它有助于确保始终使用响应内容。 当 filter 以某种方式处理响应时,必须格外小心地始终使用 其内容或以其他方式将其传播到下游,这将确保 一样。下面是一个处理状态代码的筛选器,但确保 任何响应内容(无论是否预期)都会被释放:ExchangeFunctionWebClientUNAUTHORIZEDspring-doc.cn

public ExchangeFilterFunction renewTokenFilter() {
	return (request, next) -> next.exchange(request).flatMap(response -> {
		if (response.statusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
			return response.releaseBody()
					.then(renewToken())
					.flatMap(token -> {
						ClientRequest newRequest = ClientRequest.from(request).build();
						return next.exchange(newRequest);
					});
		} else {
			return Mono.just(response);
		}
	});
}
fun renewTokenFilter(): ExchangeFilterFunction? {
	return ExchangeFilterFunction { request: ClientRequest?, next: ExchangeFunction ->
		next.exchange(request!!).flatMap { response: ClientResponse ->
			if (response.statusCode().value() == HttpStatus.UNAUTHORIZED.value()) {
				return@flatMap response.releaseBody()
						.then(renewToken())
						.flatMap { token: String? ->
							val newRequest = ClientRequest.from(request).build()
							next.exchange(newRequest)
						}
			} else {
				return@flatMap Mono.just(response)
			}
		}
	}
}