I've been using RestClient and HttpInterfaces in Spring Boot 3.2 to make calls to different external and internal services. Now I want to introduce spring cloud for service discovery to call the internal services and I can't figure out how to declare the RestClient to use service names instead of hardcoded URLs.
This is the http interface I have at the moment:
public interface UsersApi {
@GetExchange("/users")
ResponseEntity<List<UserDTO>> getUsers();
@GetExchange("/users/{userId}")
ResponseEntity<UserDTO> getUser(@PathVariable UUID userId);
}
And this is my Rest Client configuration:
@Configuration
public class RestClientConfig {
@Bean
UsersApi usersApi(){
RestClient restClient = RestClient.builder().baseUrl("https://hardcoded.user-service.url/").build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(UsersApi.class);
}
}
I know OpenFeign can be used to call service names with eureka using @FeignClient(name = "service-name"
, but since I'm already using RestClient to call external services I'd prefer to stick to using RestClient.
Also I've looked at the documentation for Spring Cloud and RestClient here: https://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/common-abstractions.html#rest-client-loadbalancer-client, but it does so definining the uri manually per method call (not as a baseUrl) and without using HttpInterfaces
Just use a @LoadBalanced RestClient.Builder
in your RestClientConfig
. You can find it set up in a working sample here with the @LoadBalanced RestClient.Builder
being configured here.