spring-cloud - 带有 Spring Cloud 和 Eureka java.lang.IllegalStateException : No instances available for localhost 的功能区

标签 spring-cloud spring-cloud-netflix netflix-ribbon

我正在使用

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

我的主课:

@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();
  }
}

我的服务电话:

@Autowired
private RestTemplate template;

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

它抛出以下异常

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)

最佳答案

当您使用 @LoadBalanced RestTemplate 时,主机名需要是 serviceId 而不是实际的主机名。在您的情况下,它正在尝试为 localhost 查找 Eureka 记录,但找不到。参见 the documentation了解如何使用多个 RestTemplate 对象,一个负载平衡,一个不平衡。

@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);
    }
}

关于spring-cloud - 带有 Spring Cloud 和 Eureka java.lang.IllegalStateException : No instances available for localhost 的功能区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569558/

相关文章:

spring-cloud - Spring Cloud 断路器或 Hystrix

spring-boot - Spring Boot应用程序无法自动连接假客户端

node.js - 如何在 nodejs 中为发现的微服务做客户端负载平衡

spring - 让功能区使用自定义 SSLContext

java - Zuul 过滤器复制流量

spring - Spring Cloud与Docker Swarm的关系

microservices - 如何使用 Zuul 路由到另一个端口

spring-boot - 使用 Zuul 作为认证网关

spring-cloud - Zuul 无法连接到 Eureka

spring-cloud - 带 List 参数的 Spring Cloud Feign Client @RequestParam 创建错误的请求