org.yes.tools.client.LoadBalancerClient Maven / Gradle / Ivy
package org.yes.tools.client;
import org.springframework.cloud.client.ServiceInstance;
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.stereotype.Component;
import reactor.core.publisher.Mono;
import java.util.concurrent.ExecutionException;
/**
* @author Co.
* @name LoadBalancerClient
* @date 2023/10/24 10:24
*/
@Component
public class LoadBalancerClient extends BlockingLoadBalancerClient {
private final ReactiveLoadBalancer.Factory loadBalancerClientFactory;
public LoadBalancerClient(ReactiveLoadBalancer.Factory loadBalancerClientFactory) {
super(loadBalancerClientFactory);
this.loadBalancerClientFactory = loadBalancerClientFactory;
}
@Override
public ServiceInstance choose(String serviceId, Request request) {
ReactiveLoadBalancer loadBalancer = this.loadBalancerClientFactory.getInstance(serviceId);
if (loadBalancer == null) {
return null;
}
Response loadBalancerResponse = null;
try {
loadBalancerResponse = Mono.from(loadBalancer.choose(request)).toFuture().get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
if (loadBalancerResponse == null) {
return null;
}
return loadBalancerResponse.getServer();
}
}