LoadBalancerAutoConfiguration负载均衡自动配置 里面调用
public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor {
private LoadBalancerClient loadBalancer;
//注入LoadBalancerClient 的实现 (唯一的实现就是RibbonLoadBalancerClient
public LoadBalancerInterceptor(LoadBalancerClient loadBalancer) {
this.loadBalancer = loadBalancer;
}
//拦截
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
final ClientHttpRequestExecution execution) throws IOException {
//从请求url里面拿到服务名
final URI originalUri = request.getURI();
String serviceName = originalUri.getHost();
//loadBalancer执行 根据服务名选择实例 发起请求 的过程
return this.loadBalancer.execute(serviceName,
new LoadBalancerRequest<ClientHttpResponse>() {
//等负载均衡选中了具体的服务以后 会来回调这个apply方法
@Override
public ClientHttpResponse apply(final ServiceInstance instance) throws Exception {
HttpRequest serviceRequest = new ServiceRequestWrapper(request,
instance);
//serviceRequest换成getUrl重写过的 继续拦截链
return execution.execute(serviceRequest, body);
}
});
}
private class ServiceRequestWrapper extends HttpRequestWrapper {
private final ServiceInstance instance;
public ServiceRequestWrapper(HttpRequest request, ServiceInstance instance) {
super(request);
this.instance = instance;
}
@Override
public URI getURI() {
//之前看的RibbonLoadBalancerClient.reconstructURI
URI uri = LoadBalancerInterceptor.this.loadBalancer.reconstructURI(
this.instance, getRequest().getURI());
return uri;
}
}
}
这个负载均衡器的拦截 完全靠注入的LoadBalancerClient决定怎么做
拦截里面 转到LoadBalancerClient.execute 里面会选中具体的服务实例 再来回调apply方法
回调的方法 里面穿的HttpRequest的getUrl 重写 里面也用LoadBalancerClient.reconstructURI 吧原来的url换掉