我最近开始使用reactive,并创建了一个使用reactive流的简单应用程序。
我有以下代码,我通过empID获得一名员工。只有当showExtraDetails
boolean设置为true
时,我才需要向API提供有关员工的额外详细信息。如果设置为false,我必须在返回employee对象之前将额外的详细信息设置为null。现在我正在使用流上的一个块来实现这一点。有没有可能在没有阻塞的情况下执行此操作,以便我的方法可以返回Mono。
下面是我已经完成的代码。
public Employee getEmployee(String empID, boolean showExtraDetails) {
Query query = new Query();
query.addCriteria(Criteria.where("empID").is(empID));
Employee employee = reactiveMongoTemplate.findOne(query, Employee.class, COLLECTION_NAME).block();
if (employee != null) {
logger.info("employee {} found", empID);
}
if (employee != null && !showExtraDetails) {
employee.getDetails().setExtraDetails(null);
}
return employee;
}
尝试这个,应该像这样工作,假设reactiveMongoTemboard
是你的mongo存储库
return reactiveMongoTemplate.findById(empID).map(employee -> {
if (!showExtraDetails) {
employee.getDetails().setExtraDetails(null);
}
return employee;
});