如何在Spring boot中修改Mono对象的属性而不阻塞它

Sky*_*lue 6 java reactive-programming spring-boot spring-webflux

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

我有以下代码,我通过 empID 获取员工。showExtraDetails仅当boolean 设置为时特别要求时,我才必须向我的 API 提供有关员工的额外详细信息true。如果它设置为 false,我必须在返回员工对象之前将额外的详细信息设置为 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;

}  
Run Code Online (Sandbox Code Playgroud)

kj0*_*007 2

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

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