使用RestClient、HttpInterfaces和Eureka调用服务名称

问题描述 投票:0回答:1

我一直在 Spring Boot 3.2 中使用 RestClient 和 HttpInterfaces 来调用不同的外部和内部服务。 现在我想引入Spring Cloud进行服务发现来调用内部服务,但我不知道如何声明RestClient以使用服务名称而不是硬编码的URL。

这是我现在的http接口:

public interface UsersApi {

    @GetExchange("/users")
    ResponseEntity<List<UserDTO>> getUsers();

    @GetExchange("/users/{userId}")
    ResponseEntity<UserDTO> getUser(@PathVariable UUID userId);

}

这是我的 Rest 客户端配置:

@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);
    }
}

我知道 OpenFeign 可用于通过 eureka 调用服务名称

@FeignClient(name = "service-name"
,但由于我已经使用 RestClient 来调用外部服务,所以我更愿意坚持使用 RestClient。

我还在这里查看了 Spring Cloud 和 RestClient 的文档:https://docs.spring.io/spring-cloud-commons/reference/spring-cloud-commons/common-abstractions.html#rest-client -loadbalancer-client,但它是在每个方法调用中手动定义 uri(不是作为 baseUrl)并且不使用 HttpInterfaces

spring-boot spring-cloud netflix-eureka
1个回答
0
投票

只需在您的

@LoadBalanced RestClient.Builder
中使用
RestClientConfig
。您可以在此处的工作示例中找到它的设置,并在
此处
配置@LoadBalanced RestClient.Builder

© www.soinside.com 2019 - 2024. All rights reserved.