Ribbon with Spring Cloud and Eureka java.lang.IllegalStateException: No instances available for localhost

atiwari54 picture atiwari54 · Jan 10, 2017 · Viewed 8.8k times · Source

I am using

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-netflix</artifactId>
  <version>1.2.3.RELEASE</version>
  <type>pom</type>
  <scope>import</scope>
</dependency>

My main class:

@SpringBootApplication
//@Configuration
@ComponentScan(basePackages = "com.mypackage")
@EnableAutoConfiguration
@EnableEurekaClient
@EnableSwagger2
public class App 
{
  public static void main( String[] args )
  {

    SpringApplication.run(App.class, args);
  }

  @LoadBalanced
  @Bean(name="template")
  RestTemplate restTemplate() {
    return new RestTemplate();
  }
}

My service calling:

@Autowired
private RestTemplate template;

ResponseEntity<String> avs = template.exchange("http://localhost:7075/xyz/json/authenticate",HttpMethod.POST ,request,String.class); 

It is throwing the following exception

java.lang.IllegalStateException: No instances available for localhost
    at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:90)
    at org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor$1.doWithRetry(RetryLoadBalancerInterceptor.java:60)
    at org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor$1.doWithRetry(RetryLoadBalancerInterceptor.java:48)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:276)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:157)

Answer

spencergibb picture spencergibb · Jan 10, 2017

When you use a @LoadBalanced RestTemplate the hostname needs to be a serviceId not an actual hostname. In your case, it's trying to find a eureka record for localhost and can't find one. See the documentation for how to use multiple RestTemplate objects, one load balanced, one not.

@Configuration
public class MyConfiguration {

    @LoadBalanced
    @Bean
    RestTemplate loadBalanced() {
        return new RestTemplate();
    }

    @Primary
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

public class MyClass {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    @LoadBalanced
    private RestTemplate loadBalanced;

    public String doOtherStuff() {
        return loadBalanced.getForObject("http://stores/stores", String.class);
    }

    public String doStuff() {
        return restTemplate.getForObject("http://example.com", String.class);
    }
}