如何在 Spring 启动时修改 Mono 对象的属性而不阻塞它

How to modify atributes of a Mono object without blocking it in Spring boot

我最近开始使用反应式并创建了一个使用反应式流的简单应用程序。

我有以下代码,我通过 empID 获得了一名员工。仅当 showExtraDetails 布尔值设置为 true 时特别要求时,我才必须向我的 API 提供有关员工的额外详细信息。如果它设置为 false,我必须在 returning 员工对象之前将额外的详细信息设置为 null。现在我正在流上使用一个块来实现这一点。是否可以不阻塞地执行此操作,以便我的方法可以 return 一个单声道。

以下是我完成的代码。

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;

}  

尝试这个,应该像这样工作,假设 reactiveMongoTemplate 是你的 mongo 存储库

return reactiveMongoTemplate.findById(empID).map(employee -> {
            if (!showExtraDetails) {
              employee.getDetails().setExtraDetails(null);
            }
            return employee;                
        });