在使用Ribbon+RestTemplate出现java.lang.IllegalStateException: No instances available for springboot-service,负载没有找到对应的名称的微服务,网上找了很多解决方案大概有以下几种:
1.服务命名问题,命名不能使用_、不能太长等,但是可以使用-。
2.访问内部注册中心的服务使用IP访问,比如:127.0.0.1。代码如下,如果负载不是内部服务去掉@LoadBalanced注解使用IP地址访问
@Bean
@LoadBalanced
public RestTemplate template() {
return new RestTemplate();
}
@Autowired
RestTemplate restTemplate;
@RequestMapping("/consumerServiceRibbon")
@HystrixCommand(fallbackMethod="consumerServiceRibbonFallback")
public String consumerServiceRibbon(@RequestBody ServiceInfo serviceInfo){
String result = this.restTemplate.postForObject("http://springboot-
service/service/rest?token=1", serviceInfo, String.class);
//内部访问使用spring.application.name访问,外包使用IP访问
return result;
}
3.我个人是使用了最新的2.4.1spring boot版本和2020.0.0-M6spring cloud版本所以代码上有所改动
@Bean
@LoadBalanced
RestOperations restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Autowired
RestOperations restTemplate;
application.propreties添加
springboot-service.ribbon.eureka.enabled= false
springboot-service.ribbon.listOfServers= localhost:8090,localhost:8091 #两个服务的地址
springboot-service.ribbon.ServerListRefreshInterval= 2000