Java 响应式程序
Java Reactive program
我的要求如下
获取将具有 apptId 的 ApptReq 对象。从 DB 获取 Appt 对象并使用来自 ApptReq 的数据更新 Appt 对象并更新 table.
Mono<User> monoUser = retrieveUser();
public Mono<ServerResponse> updateAppt(ServerRequest request) {
return apptRepository.findById(request.bodyToMono(ApptReq.class).map(ApptReq::getApptId)).flatMap(appt -> {
return updateAppt(appt, request.bodyToMono(ApptReq.class)).flatMap(apptRepository::save).flatMap(
res -> ServerResponse.created(URI.create(String.format(APPT_URI_FORMAT, res.getApptId()))).build());
});
}
private Mono<Appt> updateAppt(Appt appt, Mono<ApptReq> apptReq) {
return apptReq.map(req -> {
appt.setNotes(req.getNotes());
return monoUser.map((usr) -> {
appt.setUpdatedBy(usr.getUserId());
return appt;
});
});
}
此处在 updateAppt 方法中出现错误
can not convert from Mono<Object> to Mono<Appt>.
有没有更好的方法?
你快搞定了。我在您的 updateAppt(ServerRequest request)
方法中没有做任何更改,只是在您的 updateAppt(Appt appt, Mono<ApptReq> apptReq)
方法中稍作调整,如下所示:
private Mono<Appt> updateAppt(Appt appt, Mono<ApptReq> apptReq) {
return apptReq.flatMap(req -> {
appt.setNotes(req.getNotes());
return retrieveUser().map((usr) -> {
appt.setUpdatedBy(usr.getUserId());
return appt;
});
});
}
注意 apptReq.flatMap
而不是您的 apptReq.map
,一切正常。试一试!
提醒:小心其他 Mono
中的嵌套 Mono
或更普遍的嵌套 Publisher
。
我的要求如下
获取将具有 apptId 的 ApptReq 对象。从 DB 获取 Appt 对象并使用来自 ApptReq 的数据更新 Appt 对象并更新 table.
Mono<User> monoUser = retrieveUser();
public Mono<ServerResponse> updateAppt(ServerRequest request) {
return apptRepository.findById(request.bodyToMono(ApptReq.class).map(ApptReq::getApptId)).flatMap(appt -> {
return updateAppt(appt, request.bodyToMono(ApptReq.class)).flatMap(apptRepository::save).flatMap(
res -> ServerResponse.created(URI.create(String.format(APPT_URI_FORMAT, res.getApptId()))).build());
});
}
private Mono<Appt> updateAppt(Appt appt, Mono<ApptReq> apptReq) {
return apptReq.map(req -> {
appt.setNotes(req.getNotes());
return monoUser.map((usr) -> {
appt.setUpdatedBy(usr.getUserId());
return appt;
});
});
}
此处在 updateAppt 方法中出现错误
can not convert from Mono<Object> to Mono<Appt>.
有没有更好的方法?
你快搞定了。我在您的 updateAppt(ServerRequest request)
方法中没有做任何更改,只是在您的 updateAppt(Appt appt, Mono<ApptReq> apptReq)
方法中稍作调整,如下所示:
private Mono<Appt> updateAppt(Appt appt, Mono<ApptReq> apptReq) {
return apptReq.flatMap(req -> {
appt.setNotes(req.getNotes());
return retrieveUser().map((usr) -> {
appt.setUpdatedBy(usr.getUserId());
return appt;
});
});
}
注意 apptReq.flatMap
而不是您的 apptReq.map
,一切正常。试一试!
提醒:小心其他 Mono
中的嵌套 Mono
或更普遍的嵌套 Publisher
。