2016-04-06 53 views
4

我使用的是春天啓動1.3.3春天開機自動裝配Autowired DiscoveryClient RestTemplate的UnknownHostException

<parent> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-parent</artifactId> 
    <version>1.3.3.RELEASE</version> 
    <relativePath/> <!-- lookup parent from repository --> 
</parent> 

編輯

我使用Brixton.RC1我春雲依賴

<dependencyManagement> 
    <dependencies> 
     <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-dependencies</artifactId> 
      <version>Brixton.RC1</version> 
      <type>pom</type> 
      <scope>import</scope> 
     </dependency> 
    </dependencies> 
</dependencyManagement> 

我的應用程序設置了這些註釋:

@EnableDiscoveryClient 
@SpringBootApplication 
public class Application { 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 
} 

我在它與服務休息控制器:

@RestController 
public class MyController { 

    @Autowired 
    private MyService myService; 

而在我的服務,我嘗試使用自動裝配Autowired休息模板調用另一個尤里卡註冊服務。

@Service 
public class MyServiceImpl { 

    private final ParameterizedTypeReference<Answer> ANSWER = new ParameterizedTypeReference<Answer>() {}; 

    @Autowired 
    private DiscoveryClient discoveryClient; //just here for testing 

    @Autowired 
    private RestTemplate restTemplate; // 

    public String someCoolMethod(String input){ 
     log.info("Instance available? " + isInstanceAvailable()); 

     final RequestEntity<String> requestEntity = RequestEntity.post(URI.create("http://myotherservice/othermethod")).accept(MediaType.APPLICATION_JSON).body(input); 
     final ResponseEntity<String> response = this.restTemplate.exchange(requestEntity, ANSWER); 
     log.info(response); 
     return response.getBody(); 
    } 

    private Boolean isInstanceAvailable(){ 
     List<ServiceInstance> instances = discoveryClient.getInstances("myotherservice"); 
     for(ServiceInstance si : instances){ 
      log.info(si.getUri().toString()); 
     } 
     return instances.size() > 0; 
    } 

} 

我完全困惑,因爲我在另一個項目中工作。這裏也是輸出:

INFO http://192.168.1.10:1234 
INFO Instance available? true 
ERROR I/O error on POST request for "http://myotherservice/othermethod": myotherservice; nested exception is java.net.UnknownHostException: myotherservice 

所以我可以看到,這兩個服務都註冊了尤里卡。爲MyService能夠:

  • 與尤里卡
  • 查詢尤里卡寄存器 'myotherservice'
  • 得到與正確的主機和端口

但是,自動裝配Autowired RestTemplate拋出的UnknownHostException有效響應。

+0

您使用的是什麼版本的Spring Cloud?顯示您的春天雲依賴關係。您的'RestTemplate'未正確配置發現。 – spencergibb

回答

12

answer您需要創建一個@LoadbalancedRestTemplate截至RC1。

@Configuration 
public class MyConfiguration { 

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

非常感謝!兩次! – DaShaun

相關問題