【发布时间】:2020-10-12 15:55:47
【问题描述】:
我在 Spring Cloud Gateway 中修改 Flux 响应时遇到了一些麻烦。我的设置(简化)如下: 我有 2 个域对象:
@Data
@AllArgsConstructor
public class PersonV10 {
@NotNull
private String name;
}
@Data
@AllArgsConstructor
public class PersonV20 {
@NotNull
private String firstName;
@NotNull
private String lastName;
}
现在我的服务正在返回 PersonV20 的实例并使用 Spring Cloud Gateway 我想将响应修改为 PersonV10。在 /person 我得到一个 Flux
我的路线如下:
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("rewrite_response_v20", r -> r.path("/person/**")
.filters(f -> f.modifyResponseBody(PersonV20.class, PersonV10.class,
(exchange, p) -> Mono.just(new PersonV10(p.getFirstName() + " " + p.getLastName()))))
.uri("https://localhost:8444"))
.build();
}
当调用 /person/{id} 端点时,它工作得很好,我的响应很好地修改为 PersonV10。但是,当我现在调用 /person 端点时,我得到了一个 Flux,我在 Spring Cloud Gateway 中得到了这个异常:
org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize instance of `com.example.gateway.mutate_response_filter.PersonV20` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.example.gateway.mutate_response_filter.PersonV20` out of START_ARRAY token
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 1]
at org.springframework.http.codec.json.AbstractJackson2Decoder.processException(AbstractJackson2Decoder.java:215) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
现在我想这是有道理的,因为我得到了 Flux 作为响应,而在 modifyResponseBody 中我使用的是 Mono。但是我不清楚在这种情况下如何使用 Flux。有人可以指出我正确的方向吗?谢谢!
【问题讨论】: