Solution
The general usage of RestTemplate
coinside with Eureka
code snippet is following
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaRestTemplateExampleApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaRestTemplateExampleApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("/")
public String callOtherService() {
RestTemplate restTemplate = restTemplate();
ResponseEntity<String> response = restTemplate.exchange("http://eureka-client-service/api/endpoint", HttpMethod.GET, null, String.class);
return "Response from other service: " + response.getBody();
}
}
By the way , before configure RestTempalte
you d better make sure that both Eureka
client and server side has been configure correctly
Recommendation
Specified Ip or service name in microService with restTemplate is not recommended . because of it is too coupling , I will show your a http client request componment Fegin
1.Define a Fegin interface
The interface reference is based on Server Provider side , just type method
maintain consistency with provider side
@FeignClient("eureka-client-service")
public interface MyFeignClient {
@GetMapping("/api/endpoint")
String getEndpointData();
}
2.Make a Request
The rest of all is same as RestTemplate
, but the usage is more compact and convenient
@RestController
public class MyController {
private final MyFeignClient feignClient;
@Autowired
public MyController(MyFeignClient feignClient) {
this.feignClient = feignClient;
}
@GetMapping("/")
public String callOtherService() {
return "Response from other service: " + feignClient.getEndpointData();
}
}
Appendix
If you build project in maven , you can add following dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${yourFegin.version}</version>
</dependency>