SpringBoot使用restTemplate远程访问时报错

错误场景

SpringBoot使用restTemplate远程访问时报错
java.lang.IllegalStateException: No instances available for xxx

解决方案

这个报错一般会出现在使用了负载均衡,如:

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}

第一种方式:当使用restTemplate调用ulr的时候,不要直接写域名,http://127.0.0.1:8080/user,而是要写服务名http://user-server/user

第二种方式:重新设置restTemplate,不是用负载均衡也可以
配置代码如下:

//第一种
@Bean
@LoadBalanced
@Primary
public RestTemplate restTemplate(){
    return new RestTemplate();
}


//第二种
@Bean
public RestTemplate restTemplateCustom(){
    return new RestTemplate();
}

 

使用时引入代码如下:

@Autowired
@Qualifier("restTemplateCustom") // 根据名称来找bean
private RestTemplate restTemplateCustom;

然后url使用ip就可以了。

posted @ 2022-12-01 11:51  孤独二世  阅读(995)  评论(0编辑  收藏  举报