我刚刚开始学习spring网络流量。对于如何在反应式编程而不是命令式编程中完成工作有完全的改变或观点。
因此,我想实现一个非常简单的输出。
我有响应类,其中包含字段成功,消息和列表数据。
@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给我的信息返回响应。
所以我必须根据用户存储库更改响应,例如如果找不到用户
我尝试了很多方法,但最终我未能实现这一目标。
您不需要将Mono作为控制器的参数,可以从Spring进行标准数据绑定后接受该值。查看Spring文档中的示例:https : //docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller
您也不应从您的存储库中获取null,如果找不到该用户,您会得到一个空的Mono(因此.map
,.filter
不会调用,等等)。在这种情况下,您可以.switchIfEmpty
代替null检查。
如果您获得数据,则可以将其简单地设置.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())));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句