Skip to content

WebFlux WebClient 动态配置示例

今天尝试了下使用 WebClient 来发起 HTTP 请求,使用起来还是挺方便的。

首先要添加 spring-boot-starter-webflux 依赖:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.1.5</version>
</dependency>

下面是一段动态配置 WebClient 的代码:

java
import me.liujiajia.www.common.core.enums.MyEnv;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHeaders;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * WebClient 配置
 */
@Configuration
@RequiredArgsConstructor
@Slf4j
public class MyWebClientConfiguration {

    private static final Map<MyEnv, WebClient> clients = new HashMap<>();

    @PostConstruct
    public void initWebClients() {
        Arrays.stream(MyEnv.values()).forEach(env -> {
            clients.put(env, WebClient.builder()
                .baseUrl("svc-app-some-app.ns-" + env.name().toLowerCase())
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/xml; charset=UTF-8")
                .build());
        });
    }

    public static WebClient getWebClient(MyEnv env) {
        return clients.getOrDefault(env, WebClient.create());
    }
}

使用示例:

java
// 转发消息到其他环境
Arrays.stream(MyEnv.values()).forEach(env -> {
    // 跳过开发环境和当前环境
    if (env == MyEnv.DEV || env == myConfig.getEnv()) return;
    log.info("转发消息到环境: {}", env);
    var stringMono = MyWebClientConfiguration.getWebClient(env).post()
        .uri("/my/portal", Map.of("signature", signature, "timestamp", timestamp, "nonce", nonce, "env", myConfig.getEnv().getValue()))
        .bodyValue(requestBody)
        .retrieve()
        .bodyToMono(String.class);
    log.info("转发结果: {}", stringMono.block());
});