You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.2.2中RestClient代理配置实现求助

解决Spring Boot 3.2.2中RestClient+HttpServiceProxyFactory的代理配置问题

针对你遇到的连接超时问题,核心是给RestClient配置带代理的请求工厂——RestClient底层依赖ClientHttpRequestFactory处理请求发送,和RestTemplate的配置逻辑本质一致,只是集成方式不同。以下是具体解决方案:

基础代理配置(无认证)

直接修改现有RestClient Bean,添加代理配置的请求工厂:

@Bean
RestClient restClient(RestClient.Builder builder) {
    // 代理参数配置
    String proxyHost = "proxy1.lan.bnm.md";
    int proxyPort = 8080;
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

    // 创建带代理的请求工厂
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setProxy(proxy);

    // 为RestClient绑定该请求工厂
    return builder
            .baseUrl("https://jsonplaceholder.typicode.com/todos")
            .requestFactory(requestFactory)
            .build();
}

配置完成后,基于该RestClient创建的TodoClient发起的所有请求都会通过指定代理发送,解决连接超时问题。

带代理认证的进阶配置(如需)

如果代理需要用户名密码认证,推荐使用HttpComponentsClientHttpRequestFactory(需引入Apache HttpClient依赖):

  1. 先在pom.xml添加依赖:
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
</dependency>
  1. 修改RestClient的Bean配置:
@Bean
RestClient restClient(RestClient.Builder builder) {
    String proxyHost = "proxy1.lan.bnm.md";
    int proxyPort = 8080;
    String proxyUser = "你的代理用户名";
    String proxyPass = "你的代理密码";

    // 配置代理认证凭证
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(proxyHost, proxyPort),
            new UsernamePasswordCredentials(proxyUser, proxyPass)
    );

    // 构建带代理的HttpClient
    HttpClient httpClient = HttpClients.custom()
            .setProxy(new HttpHost(proxyHost, proxyPort))
            .setDefaultCredentialsProvider(credentialsProvider)
            .build();

    // 创建请求工厂
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

    return builder
            .baseUrl("https://jsonplaceholder.typicode.com/todos")
            .requestFactory(requestFactory)
            .build();
}

为何之前的配置不生效?

  • spring.cloud.bootstrap.proxy.*是Spring Cloud生态专属配置项,仅对Spring Cloud相关组件(如自动配置的RestTemplate、Feign等)生效,你使用的是纯Spring Boot的RestClient,因此该配置无效。
  • URL中直接拼接代理信息不符合RestClient的请求地址规范,必然报错。

内容的提问来源于stack exchange,提问作者zxc zxc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:12:55