使用RestTemplate、Eureka、nibbo的时候出错,写个日志以记之
错误信息如下:
java.lang.IllegalStateException: No instances available for localhost
at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:75) ~[spring-cloud-netflix-core-1.3.1.RELEASE.jar:1.3.1.RELEASE]
at org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor.intercept(LoadBalancerInterceptor.java:55) ~[spring-cloud-commons-1.2.2.RELEASE.jar:1.2.2.RELEASE]
at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:86) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:70) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:659) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
由于我使用了负载均衡(nibbo)内容如下:
//配置负载均衡
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
因此,所有的访问就必须以应用名访问,也就是生产者注册在Eureka中的ID,即如图所示:
修改前:
@RequestMapping("/test")
public String test(){
System.out.println(restTemplate);
System.out.println(restTemplate.getForObject(
"http://localhost:8001/dept/selectAll", List.class));
return "Hello";
}
修改后:
@RequestMapping("/test")
public String test(){
System.out.println(restTemplate);
System.out.println(restTemplate.getForObject(
"http://SPRINGCLOUD-PROVIDER-DEPT-8001/dept/selectAll",
List.class));
return "Hello";
}
通过分析我知道了,不能直接通过URL去访问,需要通过生产者名称来访问。