spring-cloud-openfeign icon indicating copy to clipboard operation
spring-cloud-openfeign copied to clipboard

Support to set loadBalancerKey from request header

Open alan-tang-tt opened this issue 4 years ago • 1 comments
trafficstars

When I write myself MyRule implements IRule, the key is always null, like below:

public class MyRule extends AbstractLoadBalancerRule {

    @Override
    public Server choose(Object key) {
          // here the key is always null
    }
}

By watching the source code, I find there's no where to set this loadBalancerKey. So I push this PR to resolve this problem by overriding FeignLoadBalancer#customizeLoadBalancerCommandBuilder method.

         // override FeignLoadBalancer#customizeLoadBalancerCommandBuilder
	@Override
	protected void customizeLoadBalancerCommandBuilder(RibbonRequest request, IClientConfig config, LoadBalancerCommand.Builder<RibbonResponse> builder) {
		builder.withServerLocator(request.request.headers().get("loadBalancerKey"));
	}

By this way, I can put my loadBalancerKey from feign.RequestInterceptor implementation like this:

public class MyRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        template.header("loadBalancerKey", "gray");
    }
}

Then in MyRule I can get the key:

public class MyRule extends AbstractLoadBalancerRule {

    @Override
    public Server choose(Object key) {
          // no the key equals to gray
    }
}

This is all.

alan-tang-tt avatar Dec 27 '20 09:12 alan-tang-tt

Codecov Report

Merging #451 (fdbc0c7) into 2.2.x (e32b10b) will increase coverage by 0.18%. The diff coverage is 100.00%.

Impacted file tree graph

@@             Coverage Diff              @@
##              2.2.x     #451      +/-   ##
============================================
+ Coverage     77.80%   77.98%   +0.18%     
- Complexity      476      477       +1     
============================================
  Files            64       64              
  Lines          1883     1885       +2     
  Branches        265      265              
============================================
+ Hits           1465     1470       +5     
+ Misses          298      295       -3     
  Partials        120      120              
Impacted Files Coverage Δ Complexity Δ
...work/cloud/openfeign/ribbon/FeignLoadBalancer.java 70.14% <100.00%> (+0.91%) 7.00 <1.00> (+1.00)
...ncer/RetryableFeignBlockingLoadBalancerClient.java 70.76% <0.00%> (+4.61%) 11.00% <0.00%> (ø%)

codecov[bot] avatar Dec 27 '20 09:12 codecov[bot]