首页 > 解决方案 > 在 Spring webflux 中处理条件响应的正确方法是什么

问题描述

我刚刚开始学习 Spring Web Flux。并且对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。

所以,我想实现一个非常简单的输出。

我有包含字段成功、消息和列表数据的响应类。

@Data
@Accessors(chain = true)
public class Response {

    private boolean success;
    private String message;
    private List data;
}

和一个请求类

@Data
@Accessors(chain = true)
public class LoginRequest {

    private String email;
    private String password;
}

我也有带有 webFlux 的 userRepository。

Mono<User> findUserByEmail(String email);

我有这样的登录操作。

@PostMapping("/login")
public Mono<Response> login(@RequestBody Mono<LoginRequest> request) {
}

现在我必须根据 userRepository 给我的内容返回响应。

所以我必须根据用户存储库更改响应,比如找不到用户

我尝试了很多方法,但最后我未能实现这一目标。

标签: javaspringspring-bootreactive-programmingspring-webflux

解决方案


您不需要 Mono 作为控制器的参数,您可以接受来自 Spring 的标准数据绑定后的值。查看 Spring 文档以获取示例:https ://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller

你也不应该从你的 repo 中得到 null,如果找不到用户,你会得到一个空的 Mono(所以.map,.filter等不会被调用)。在这种情况下,您可以.switchIfEmpty用作空检查的替代品。

如果您获得数据,您可以将其简单地.map用于您需要的数据,因为您不需要阻止任何其他数据:

public Mono<Response> login(LoginRequest request) {
        return repo.findUserByEmail(request.getEmail())
            .map(user ->
                Objects.equals(request.getPassword(), user.getPassword())
                    ? new Response(true, "Welcome", Collections.emptyList())//populate list here
                    : new Response(false, "invalid password", Collections.emptyList()))
            //user wasn't found in the repo
            .switchIfEmpty(Mono.just(new Response(false, "No user found", Collections.emptyList())));
    }

推荐阅读