UnknowhHostException 使用 spring-cloud-starter-gateway with spring boot 2.4.0 及以上版本

UnknowhHostException using spring-cloud-starter-gateway with spring boot 2.4.0 and above

https://github.com/reactor/reactor-netty/issues/1431相关。

Spring 云网关服务器正常启动,但通过网关请求失败,出现以下异常:

java.net.UnknownHostException: failed to resolve 'myserver' after 4 queries
at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ? org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
|_ checkpoint ? org.springframework.cloud.sleuth.instrument.web.TraceWebFilter [DefaultWebFilterChain]
|_ checkpoint ? org.springframework.boot.actuate.metrics.web.reactive.server.MetricsWebFilter [DefaultWebFilterChain]
|_ checkpoint ? HTTP GET "/service/api/applications/123" [ExceptionHandlingWebHandler]
Stack trace:
at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013)
at io.netty.resolver.dns.DnsResolveContext.tryToFinishResolve(DnsResolveContext.java:966)
at io.netty.resolver.dns.DnsResolveContext.query(DnsResolveContext.java:414)
at io.netty.resolver.dns.DnsResolveContext.onResponse(DnsResolveContext.java:601)
at io.netty.resolver.dns.DnsResolveContext.access0(DnsResolveContext.java:63)
at io.netty.resolver.dns.DnsResolveContext.operationComplete(DnsResolveContext.java:458)
.....

Works correctly when downgrading spring boot.

通过添加以下 bean 定义修复:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.netty.resolver.DefaultAddressResolverGroup;
import reactor.netty.http.client.HttpClient;

@Configuration
public class TempFixConfig {

    @Bean
    public HttpClient webClient() {
        return HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
    }
}

如果您不想更改 HttpClient bean 的创建逻辑,您可以添加一个 HttpClient Customizer:

import org.springframework.cloud.gateway.config.HttpClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.netty.resolver.DefaultAddressResolverGroup;
import reactor.netty.http.client.HttpClient;

@Configuration
public class HttpClientResolverFixConfig {

    @Bean
    public HttpClientCustomizer httpClientResolverCustomizer() {
        return new HttpClientCustomizer() {

            @Override
            public HttpClient customize(HttpClient httpClient) {
                return httpClient.resolver(DefaultAddressResolverGroup.INSTANCE);
            }
        };
    }

}