定位到BlockingLoadBalancerClient.java 155行
出问题的点代码如下: Response<ServiceInstance> loadBalancerResponse = Mono.from(loadBalancer.choose(request)).block();
将这段修改为异步解决:
新建一个新的类
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties; import org.springframework.cloud.client.loadbalancer.Request; import org.springframework.cloud.client.loadbalancer.Response; import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer; import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; import reactor.core.publisher.Mono;import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException;/*** 1* @author: ly* @date: 2022/3/4 16:53* @version:*/ public class CustomBlockingLoadBalancerClient extends BlockingLoadBalancerClient {private final ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerClientFactory;/*** @deprecated in favour of* {@link BlockingLoadBalancerClient#BlockingLoadBalancerClient(ReactiveLoadBalancer.Factory)}* @param loadBalancerClientFactory* @param properties*/public CustomerBlockingLoadBalancerClient(LoadBalancerClientFactory loadBalancerClientFactory, LoadBalancerProperties properties) {super(loadBalancerClientFactory, properties);this.loadBalancerClientFactory = loadBalancerClientFactory;}public CustomerBlockingLoadBalancerClient(ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerClientFactory) {super(loadBalancerClientFactory);this.loadBalancerClientFactory = loadBalancerClientFactory;}@Overridepublic <T> ServiceInstance choose(String serviceId, Request<T> request) {ReactiveLoadBalancer<ServiceInstance> loadBalancer = loadBalancerClientFactory.getInstance(serviceId);if (loadBalancer == null) {return null;}CompletableFuture<Response<ServiceInstance>> f = CompletableFuture.supplyAsync(() -> {Response<ServiceInstance> loadBalancerResponse = Mono.from(loadBalancer.choose(request)).block();return loadBalancerResponse;});Response<ServiceInstance> loadBalancerResponse = null;try {loadBalancerResponse = f.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}if (loadBalancerResponse == null) {return null;}return loadBalancerResponse.getServer();} }
替换官方的bean 即可
@Autowired private LoadBalancerClientFactory loadBalancerClientFactory;@Bean public LoadBalancerClient blockingLoadBalancerClient() {return new CustomBlockingLoadBalancerClient(loadBalancerClientFactory); }