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

Multiple annotated @LoadBalanced RestTemplate doesn't work

Open fjmpaez911 opened this issue 9 years ago • 22 comments

I am facing problems when in micro service (A) I try to call to micro service (B) and micro service (C) with @LoadBalanced. If I only deploy (A) and (B) all is working fine, if I deploy (A) and (C) all is working fine, but if these three services are UP only (B) or (C) is reachable by (A), the another one is responding with 404 and I can see that the unreachable service is been resolved with the real direction for the other one. I tried without @LoadBalanced and all is working fine for these three services.

Is possible do that? What could be the problem? Thanks in advance

fjmpaez911 avatar Mar 31 '17 16:03 fjmpaez911

That should be possible. Unfortunately, you haven't provided enough information for us to make any guesses even. A sample project would be very helpful.

spencergibb avatar Mar 31 '17 16:03 spencergibb

In service A I have configurated in differents files:

@Bean("loadBalancedServiceB")
    @LoadBalanced
    public RestTemplate serviceBRestTemplate(...){}
@Bean("loadBalancedServiceC")
    @LoadBalanced
    public RestTemplate serviceCRestTemplate(...){}

Then I have:

public class WorkingImpl {

@Autowired
    @Qualifier("loadBalancedServiceB")
    private RestTemplate templateServiceB;

@Autowired
    @Qualifier("loadBalancedServiceC")
    private RestTemplate templateServiceC;

One of then is working fine but the another one is getting 404. Randomly only one is working fine.


ResponseEntity<SmsMessageResponse> response = templateServiceB.exchange(
                    uriBuilder.build().encode().toUri(), HttpMethod.POST, httpEntity,
                    Object.class);

ResponseEntity<SmsMessageResponse> response = templateServiceC.exchange(
                    uriBuilder.build().encode().toUri(), HttpMethod.POST, httpEntity,
                    Object.class);

If I only have service A and B all is working fine. The problem comes when I try to call 2 micro services.

Let me know if is not enough information and I'll do an entire example and I'll share with you.

Thanks

fjmpaez911 avatar Mar 31 '17 16:03 fjmpaez911

@fjmpaez911 please don't cross post. Pick one place and close the other http://stackoverflow.com/questions/43145273/multiple-annotated-loadbalanced-resttemplate-doesnt-work

You shouldn't need more than one @LoadBalanced rest template. The hostname should be the service id you are calling.

spencergibb avatar Mar 31 '17 16:03 spencergibb

You are right. I did with only one @LoadBalanced rest template and works as I expected. Thank you for your time and your help. I removed the post in stackoverflow, sorry for that.

fjmpaez911 avatar Apr 01 '17 15:04 fjmpaez911

Why did you reopen?

spencergibb avatar Apr 03 '17 17:04 spencergibb

Sorry but the problem still persists.

I can see that in this class ZoneAwareLoadBalancer.class I am not getting the expected response:

public Server chooseServer(Object key) {
        if (!ENABLED.get() || getLoadBalancerStats().getAvailableZones().size() <= 1) {
            logger.debug("Zone aware logic disabled or there is only one zone");
            return `super.chooseServer(key)`;
        }
...
}

This method getLoadBalancerStats() is returning:

Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.20.212:50081;	Zone:defaultZone;	Total Requests:3;	Successive connection failure:1;	Total blackout seconds:0;	Last connection made:Mon Apr 03 18:34:43 CEST 2017;	Last connection failure: Mon Apr 03 18:35:46 CEST 2017;	First connection made: Mon Apr 03 18:32:23 CEST 2017;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:22055.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:1060.0;	max resp time:62966.0;	stddev resp time:28931.799125990536]
, [Server:192.168.20.212:49960;	Zone:defaultZone;	Total Requests:2;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Mon Apr 03 18:52:37 CEST 2017;	First connection made: Mon Apr 03 18:37:26 CEST 2017;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:1992.5;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:283.0;	max resp time:3702.0;	stddev resp time:1709.5]
]

Server:192.168.20.212:50081 Server:192.168.20.212:49960

As you can see there are two micro services, one in the port 50081 (this is the one that I am calling in this concrete unit test) and another one in the port 49960.

Now in super.chooseServer(key):

public Server chooseServer(Object key) {
        if (counter == null) {
            counter = createCounter();
        }
        counter.increment();
        if (rule == null) {
            return null;
        } else {
            try {
                return rule.choose(key);
            } catch (Exception e) {
                logger.warn("LoadBalancer [{}]:  Error choosing server for key {}", name, key, e);
                return null;
            }
        }
    }

rule.choose(key); Is getting the implementation from RoundRobinRule.class

@Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

getLoadBalancer() And this method getLoadBalancer() is returning:

DynamicServerListLoadBalancer:{NFLoadBalancer:name=maroc-ma-sms,current list of Servers=[192.168.20.212:49960],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:1;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]
},Server stats: [[Server:192.168.20.212:49960;	Zone:defaultZone;	Total Requests:2;	Successive connection failure:0;	Total blackout seconds:0;	Last connection made:Mon Apr 03 18:48:00 CEST 2017;	First connection made: Mon Apr 03 18:36:28 CEST 2017;	Active Connections:0;	total failure count in last (1000) msecs:0;	average resp time:6785.0;	90 percentile resp time:0.0;	95 percentile resp time:0.0;	min resp time:207.0;	max resp time:13363.0;	stddev resp time:6578.0]
]}ServerList:org.springframework.cloud.netflix.ribbon.eureka.DomainExtractingServerList@2310eb9d

Server:192.168.20.212:49960 At this point, where is the Server:192.168.20.212:50081? I am expecting this one here.

And I can see that if I will be able to have the two servers at this point the next problem will be that in RoundRobinRule.class

@Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

choose(

public Server choose(ILoadBalancer lb, Object key) {
...
            server = allServers.get(nextServerIndex);

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }
...
}

allServers.get(nextServerIndex); if (server.isAlive() && (server.isReadyToServe())) {

It should look for the correct one, doesn't it?

And another thing that I don't understand is why the logs print:

h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {}->http://192.168.20.212:50081][total kept alive: 1; route allocated: 1 of 5; total allocated: 1 of 10]

h.i.c.PoolingHttpClientConnectionManager : Connection leased: [id: 0][route: {}->http://192.168.20.212:50081][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]

o.a.http.impl.execchain.MainClientExec   : Executing request POST _/myUrlMicroServiceB_ HTTP/1.1

When I'm calling to the micro service located on port 50081 the first time (I mean, there isn't a previous request to the other micro service, all time so far we are calling only the micro service located on port 50081 (micro service B)).

And now we are calling to the other micro service located on 49960 (micro service C) and the logs are:

h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {}->http://192.168.20.212:49960][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]

h.i.c.PoolingHttpClientConnectionManager : Connection leased: [id: 1][route: {}->http://192.168.20.212:49960][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]

o.a.http.impl.execchain.MainClientExec   : **Opening connection** {}->http://192.168.20.212:49960

.i.c.DefaultHttpClientConnectionOperator : **Connecting to** /192.168.20.212:49960

.i.c.DefaultHttpClientConnectionOperator : **Connection established** 192.168.20.212:56043<->192.168.20.212:49960

o.a.http.impl.execchain.MainClientExec   : Executing request POST _/myUrlMicroServiceC_ HTTP/1.1

Here I can see more logs that the previous time when we are calling the micro service B. And now if I try to call again the micro service B I can see that the logs are wrong:

h.i.c.PoolingHttpClientConnectionManager : Connection request: [route: {}->http://192.168.20.212:49960][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10]

h.i.c.PoolingHttpClientConnectionManager : Connection leased: [id: 2][route: {}->http://192.168.20.212:49960][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10]

o.a.http.impl.execchain.MainClientExec   : Opening connection {}->http://192.168.20.212:49960

.i.c.DefaultHttpClientConnectionOperator : Connecting to /192.168.20.212:49960

.i.c.DefaultHttpClientConnectionOperator : Connection established 192.168.20.212:57884<->192.168.20.212:49960

o.a.http.impl.execchain.MainClientExec   : Executing request POST _/myUrlMicroServiceB_ HTTP/1.1

fjmpaez911 avatar Apr 03 '17 17:04 fjmpaez911

I'm sorry, none of that is helpful to me to try and help you.

A sample project would be very helpful.

spencergibb avatar Apr 03 '17 17:04 spencergibb

@spencergibb I think that the SpringClientFactory when it is trying to resolve beantype=ILoadBalancer from the service-name context, it is always retrieving the same ILoadBalancer that sometimes doest belong to the service-name context requested.

Question here about Ribbon in general, If you are using RestTemplate for multiple service ids, do we need to define a different IClientConfig for each service we are trying to call ; that we need to define different IClientConfig.clientName for each Ribbon client ?

hodeh avatar Apr 03 '17 20:04 hodeh

@hodeh I've never seen that happen. Having a project that recreates that would be very helpful. IClientConfig should be created automatically for each ribbon client.

spencergibb avatar Apr 03 '17 20:04 spencergibb

@spencergibb here you are an entire example loadBalancedIssue

You have to run the 4 microservices and here is the problem // FIXME: Here the first call is reaching msvc-b but the second one is is reaching msvc-c

Tell me if you need something else

Thanks in advance

fjmpaez911 avatar Apr 03 '17 20:04 fjmpaez911

@spencergibb do you need to define multiple @RibbonClient annotation for each service client we are trying to call ? is it ok if it was not there at all. ( we are not defining any implying that we want to use the defaults for all services ribbon clients with no custom IClientConfigs) could that be the issue that they all resolve to the same ILoadBalancer ?

hodeh avatar Apr 03 '17 20:04 hodeh

No need. It should not cause the issue.

spencergibb avatar Apr 03 '17 20:04 spencergibb

@fjmpaez911 no instructions on how to replicate, urls to hit, etc...

spencergibb avatar Apr 03 '17 20:04 spencergibb

Sorry @spencergibb

When the 4 services are UP you need to hit this url

curl --request GET \
  --url http://localhost:8666/v1.0/request 

correspond to micro service a. First time all is working fine.

If you hit this url again you will see that all time micro service c is hit and the micro service B is never reached again

fjmpaez911 avatar Apr 03 '17 20:04 fjmpaez911

The problem is that you defined a shared IRule in SPXRibbonConfigurator. Rather than define it in a @Configuration class that is picked up by component scanning, define it as the default configuration below.

@RibbonClients(defaultConfiguration = SPXRibbonConfigurator.class)

spencergibb avatar Apr 03 '17 20:04 spencergibb

Thank you so much @spencergibb! now is working as we expected. Thank you for your time again

fjmpaez911 avatar Apr 03 '17 21:04 fjmpaez911

What if one use RestTemplates with different configuration? Isn't it a case where one might need to create multiple RestTemplate beans?

rvcoutinho avatar Aug 27 '17 20:08 rvcoutinho

@rvcoutinho please open a separate issue with your question if our docs do not answer your question http://cloud.spring.io/spring-cloud-static/Dalston.SR3/#_multiple_resttemplate_objects

ryanjbaxter avatar Aug 29 '17 15:08 ryanjbaxter

@ryanjbaxter ,How to provide separate ribbon configuration for separate rest template? I know in Feign client we can have separate configuration ,but how we will have separate configuration for separate rest template

AnkushNakaskar avatar Mar 16 '18 04:03 AnkushNakaskar

@AnkushNakaskar Please open a separate issue or post an issue on StackOverflow or ask on Gitter. Please provide an example of what you are trying to accomplish so we can better assist you.

ryanjbaxter avatar Mar 16 '18 11:03 ryanjbaxter