【发布时间】:2022-01-08 18:14:56
【问题描述】:
我正在尝试从我的 Spring Cloud Gateway 服务调用另一个服务。
在 AuthenticationServiceClient 中 Webclient 应该调用所需的服务,但它没有。
我找不到我做错了什么。
这是AuthenticationServiceClient.class的实现:
public class AuthenticationServiceClientImpl implements AuthenticationServiceClient {
private final WebClient webClient;
@Autowired
public AuthenticationServiceClientImpl(WebClient.Builder builder) {
this.webClient = builder.baseUrl("http://localhost:9002").build();
}
@Override
public Mono<AppUser> getAppUser(String accessToken) {
return this.webClient.get().uri
(uriBuilder ->
uriBuilder
.path("/api/authentication-service/get-user-detail")
.queryParam("accessToken", accessToken)
.build()
)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(HttpStatus::isError, error -> Mono.just(new RuntimeException("Error from AUTHENTICATION SERVICE")))
.bodyToMono(AppUser.class);
}
}
这是AuthenticationFilter.class:
public class AuthenticationFilter implements GatewayFilter {
private final AuthenticationServiceClient authClient;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
final String token = this.getAuthHeader(request);
authClient.getAppUser(token).flatMap(response -> {
System.out.println(response);
this.populateRequestWithHeaders(exchange, response);
return chain.filter(exchange);
});
return this.onError(exchange, "Authorization header is invalid", HttpStatus.UNAUTHORIZED);
}
}
为简洁起见,省略了一些代码和注释。
【问题讨论】:
-
不确定您是如何实现 populateRequestWithHeaders() 方法的,但要修改您需要变异的请求。在此处查看示例 - programcreek.com/java-api-examples/…
-
"在您订阅之前什么都不会发生。" - 你有一个悬挂的 Mono,你使用 authClient
标签: java spring-webflux spring-cloud-gateway spring-webclient