/** * Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient * @author Spencer Gibb */ @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Qualifier public@interface LoadBalanced { }
/** * Represents a client side load balancer * @author Spencer Gibb */ publicinterfaceLoadBalancerClientextendsServiceInstanceChooser{
<T> T execute(String serviceId, LoadBalancerRequest<T> request)throws IOException;
<T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request)throws IOException; URI reconstructURI(ServiceInstance instance, URI original); }
URI reconstructURI(ServiceInstance instance, URI original):使用主机 ip、port 构建特定的 URI,供 RIbbon 内部使用。Ribbon 使用服务名称的 URI 作为host。如:http://instance-id/path/to/service
publicLoadBalancerInterceptor(LoadBalancerClient loadBalancer){ // for backwards compatibility this(loadBalancer, new LoadBalancerRequestFactory(loadBalancer)); }
@Override public ClientHttpResponse intercept(final HttpRequest request, finalbyte[] body, final ClientHttpRequestExecution execution)throws IOException { final URI originalUri = request.getURI(); String serviceName = originalUri.getHost(); Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri); returnthis.loadBalancer.execute(serviceName, requestFactory.createRequest(request, body, execution)); } }
publicinterfaceIRule{ /* * choose one alive server from lb.allServers or * lb.upServers according to key * * @return choosen Server object. NULL is returned if none * server is available */
public Server choose(Object key); publicvoidsetLoadBalancer(ILoadBalancer lb); public ILoadBalancer getLoadBalancer(); }