2016-04-06 2 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 

Таким образом, я вижу, что обе службы зарегистрированы в Eureka. MyService способен:

  • регистр с Eureka
  • запроса Eureka для '' 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

Смежные вопросы