ati*_*i54 2 spring-cloud netflix-ribbon spring-cloud-netflix
我在用
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix</artifactId>
<version>1.2.3.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我的主班:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的服务电话:
@Autowired
private RestTemplate template;
ResponseEntity<String> avs = template.exchange("http://localhost:7075/xyz/json/authenticate",HttpMethod.POST ,request,String.class);
Run Code Online (Sandbox Code Playgroud)
它抛出以下异常
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)
Run Code Online (Sandbox Code Playgroud)
使用时@LoadBalanced RestTemplate,主机名需要是serviceId而不是实际的主机名。在您的情况下,它正在尝试查找一个尤里卡记录,localhost而找不到一个。有关如何使用多个对象的信息,请参阅文档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);
}
}
Run Code Online (Sandbox Code Playgroud)