How to use WebClient in SpringCloud gateway to asynchronously call a microservice?
To make asynchronous calls to microservices using WebClient in Spring Cloud Gateway, follow these steps:
- Add dependencies: include the dependencies for WebClient and Spring Cloud Gateway in the project’s pom.xml file.
<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- WebClient -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
- Create a GatewayFilter: Create a GatewayFilter to handle requests and use WebClient to asynchronously call the microservice.
@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {
private final WebClient webClient;
public MyGatewayFilter(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.build();
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 异步调用微服务
Mono<ClientResponse> responseMono = webClient.get()
.uri("http://microservice/service")
.exchange();
// 处理响应
return responseMono.flatMap(response -> {
// 复制响应状态码、头部信息等
ServerHttpResponse serverResponse = exchange.getResponse();
serverResponse.setStatusCode(response.statusCode());
serverResponse.getHeaders().putAll(response.headers().asHttpHeaders());
// 转发响应体
return response.bodyToMono(String.class)
.flatMap(body -> {
serverResponse.getHeaders().setContentLength(body.length());
return serverResponse.writeWith(Mono.just(serverResponse.bufferFactory().wrap(body.getBytes())));
});
});
}
@Override
public int getOrder() {
return -1;
}
}
- Configure a GatewayFilter: Set up the GatewayFilter in the application’s configuration file.
spring:
cloud:
gateway:
routes:
- id: my_route
uri: http://localhost:8080/
filters:
- MyGatewayFilter
In this way, when routing with Spring Cloud Gateway, the MyGatewayFilter will be automatically invoked to handle the request and use WebClient to asynchronously call the microservices.