我正在使用
<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/