4

私はスプリングブート1.3.3を使用しています

<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 rest テンプレートを使用して、別の eureka 登録済みサービスを呼び出そうとしています。

@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 に「myotherservice」を問い合わせる
  • 正しいホストとポートで有効な応答を得る

しかし、自動配線された RestTemplate は UnknownHostException をスローしています。

4

1 に答える 1

12

答え@Loadbalanced RestTemplateは、RC1 の時点で作成する必要があるということです。

@Configuration
public class MyConfiguration {

    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
于 2016-04-07T19:49:50.147 に答える