【问题标题】:How to modify atributes of a Mono object without blocking it in Spring boot如何在 Spring Boot 中修改 Mono 对象的属性而不阻塞它
【发布时间】:2019-02-23 21:06:55
【问题描述】:

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

我有以下代码,我通过 empID 获得了一名员工。只有当showExtraDetails boolean 设置为true 时特别要求时,我才必须向我的 API 提供有关该员工的额外详细信息。如果它设置为 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;

}  

【问题讨论】:

    标签: java spring-boot reactive-programming spring-webflux


    【解决方案1】:

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

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

    【讨论】:

    • 这里不需要 flatMap,map 也可以做同样的工作。 reactiveMongoTemplate.findById(empID).map(employee ->employee.getDetails().setExtraDetails(null))
    • 在空的情况下不执行map算子,所以map这里是个不错的选择。
    • 这是否意味着我不必进行单独的空检查? @BrianClozel
    • 根据反应流规范,MonoFlux 不允许提供 null 元素。所以 Mono 要么提供一个元素,要么什么都不提供 (Mono.empty())
    猜你喜欢
    • 2020-12-26
    • 2021-01-28
    • 1970-01-01
    • 2017-09-17
    • 2019-10-19
    • 2020-03-09
    • 2023-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多