zoukankan      html  css  js  c++  java
  • Spring Boot+Cloud RestTemplate 调用IP或域名

    在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;
  • 相关阅读:
    BoundsChecker下载
    大型系统内部资源定位的途径
    架构的焦点
    为什么日志只应该有三个级别
    回收站引发ORACLE查询表空间使用缓慢
    题目记录
    广搜入门 待改进的广搜
    归并排序的使用
    大数数组中滚动数组的应用
    多重背包问题
  • 原文地址:https://www.cnblogs.com/rench/p/6236756.html
Copyright © 2011-2022 走看看