我正在做一个POC,关于Apache Camel是否能满足我作为一个请求聚合器的要求。
比方说,我有一个现有的系统,我在两个不同的服务上创建用户。因此,我希望用Camel将这两个步骤聚合成一个单一的聚合请求。我有两个不同的问题。
@Component
public class DemoRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
restConfiguration()
.component("servlet")
.bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true");
rest("/api/v1")
.description("Create user flow")
.id("create-user")
.consumes(MediaType.APPLICATION_JSON_VALUE)
.produces(MediaType.APPLICATION_JSON_VALUE)
.post("/user")
.to("direct:createUser");
from("direct:createUser")
.log(" :: ${body} ")
.marshal().json(JsonLibrary.Jackson)
.unmarshal().json(JsonLibrary.Jackson, DemoUserRequest.class)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
Message message = exchange.getIn();
DemoUserRequest demoUserRequest = exchange.getIn(DemoUserRequest.class);
log.info("DemoUserRequest toString : " + demoUserRequest.toString());
DemoUserMS1Request demoUserMS1Request = new DemoUserMS1Request(demoUserRequest.getUserID(),
demoUserRequest.getUserName(),
demoUserRequest.getUserLanguage(),
demoUserRequest.getUserName()
.substring(0, demoUserRequest.getUserName().indexOf(' ')));
message.setBody(demoUserMS1Request);
}
})
.marshal().json(JsonLibrary.Jackson, DemoUserMS1Request.class)
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
// .toD("{{ms1.url}}/api/createUser");
.to("stream:out");
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class DemoUserRequest {
private String userID;
private String userName;
private String userLanguage;
}
@Data
@AllArgsConstructor
public class DemoUserMS1Request {
private String userID;
private String userName;
private String userLanguage;
private String userFirstName;
}
@Data
public class DemoUserMS2Request {
private String userName;
}
我在请求
curl --location --request POST 'http://localhost:8081/api/v1/user' \
--header 'Content-Type: application/json' \
--data-raw '{
"userID" : "1",
"userName" : "abc def",
"userLanguage" : "EN"
}'
骆驼抛出的错误有
java.lang.NullPointerException
at com.unbxd.hagrid.routes.DemoRoute$1.process(DemoRoute.java:42)
[在log.info行]有什么办法可以把我的JSON请求投到我的POJOs中吗?
在你有的地方。
DemoUserRequest demoUserRequest = exchange.getIn(DemoUserRequest.class);
你应该改成:
DemoUserRequest demoUserRequest = exchange.getIn().getBody(DemoUserRequest.class);