Spring Boot+Cloud RestTemplate 调用IP或域名

 转载 https://www.jianshu.com/p/0db3570e4674

 

在SpringBoot+Cloud的项目中,我们使用了自动配置的OAuth2RestTemplate,RestTemplate,但是在使用这些restTemplate的时候,url必须是服务的名称,如果要调用真实的域名或者ip的url,会有错误,如下:

 

UriComponents b = UriComponentsBuilder.fromUriString("http://www.baidu.com").build();
String str  = rest.getForObject(b.toUri(), String.class);

错误

 

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: No instances available for www.baidu.com

查看错误的跟踪链发现,自动注入的restTemplate中加入了cloud.netflix*包下面的interceptor,所以默认会通过RibbonLoadBalancerClient去查找注册中心的instances,如上面的代码,www.baidu.com肯定不存在,所以就报错了。

找了半天,解决方案是,自己自定义或者产生一个resttemplate即可,不使用自动配置的。

 

@Bean(name="remoteRestTemplate")
public RestTemplate restTemplate() {
    return new RestTemplate();
}

 

@Autowired
private OAuth2RestTemplate o2rest;
@Autowired
@Qualifier(value = "remoteRestTemplate")
private RestTemplate rest;


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值