java在reactor中流动多个对象的有效/正确方法是什么
我不熟悉反应式编程,为了得到我的手,我试图建立一个接近真实的例子
当你看到反应堆教程时,他们会向你展示非常简单的例子,比如
return userRepository.findById(1);
或者像处理flux之类的东西,打破“brown little fox”字符串,找到唯一的字母等等。但这些教程大多只针对单个对象,不幸的是,我找不到任何指南或教程,其中显示了并排的示例,先按命令,然后按反应,这就是为什么我看到很多反应式编程的新手面临很多学习问题
但我的观点是,在现实生活中,我们处理多个对象,比如下面我在reactor中编写的示例代码。为我仍在学习的糟糕代码道歉
public Mono<ServerResponse> response(ServerRequest serverRequest) {
return
Mono.just(new UserRequest())
.map(userRequest -> {
Optional<String> name = serverRequest.queryParam("name");
if (name.isPresent() && !name.get().isEmpty()) {
userRequest.setName(name.get());
return userRequest;
}
throw new RuntimeException("Invalid name");
})
.map(userRequest -> {
Optional<String> email = serverRequest.queryParam("email");
if (email.isPresent() && !email.get().isEmpty()) {
userRequest.setEmail(email.get());
return userRequest;
}
throw new RuntimeException("Invalid email");
})
.map(userRequest -> {
userRequest.setUuid(UUID.randomUUID().toString());
return userRequest;
})
.flatMap(userRequest ->
userRepository
.findByEmail(userRequest.getEmail())
.switchIfEmpty(Mono.error(new RuntimeException("User not found")))
.map(user -> Tuples.of(userRequest, user))
)
.map(tuple -> {
String cookiePrefix = tuple.getT2().getCode() + tuple.getT1().getUuid();
return Tuples.of(tuple.getT1(), tuple.getT2(), cookiePrefix);
})
//Some more chaining here.
.flatMap(tuple ->
ServerResponse
.ok()
.cookie(ResponseCookie.from(tuple.getT3(), tuple.getT2().getRating()).build())
.bodyValue("Welcome")
);
}
考虑上面的代码,首先我用UserRequest对象来映射这个对象中的查询字符串。 然后,我需要一些数据从数据库等反应链继续更多的工作要做。 现在考虑一下
- 来自第一个链接方法的UserRequest对象和
- 我从数据库中获取的用户文档 然后我会做更多的操作,但在链接结束时,我需要这两个对象来处理最终的响应。 我在谷歌上找到的实现这一点的唯一方法是Tuple。 但是在那之后,代码看起来更脏了,因为在接下来的每一个操作符中,我都必须这样做
tuple.getT()
tuple.getT2()
最后我想问的是,这是正确的方法,还是我遗漏了什么。因为我学到了一个反应性的东西,数据流在逻辑的中间,就像在命令中一样,我们需要另一个变量/对象,所以我在上面定义并使用它,但是在第五或第六操作符之后的反应中,当开发者实现OHH时,我也需要这个对象,这是我在第二操作符中创建的,然后我必须回去。通过链锁进入我的第五或第六个接线员是正确的方法
共 (0) 个答案