[英]How to combine Mono and Flux as parameters to create new Mono?
My REST controller method should return Mono which must be built of 2 parallel requests to another web services and processing their response where one request return Mono and another request return Flux 我的REST控制器方法应该返回Mono,该Mono必须由对另一个Web服务的2个并行请求构成,并处理它们的响应,其中一个请求返回Mono,而另一个请求返回Flux
How to combine responses of Mono with Flux and process them? 如何将Mono与Flux的响应结合起来并进行处理?
Model: 模型:
@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ClassModel {
@Id
private String id;
private String roomNr;
private String className;
private String teacherId;
private List<String> studentIds;
public void addStudentId(String studentId) {
studentIds.add(studentId);
}
}
Controller: 控制器:
public Mono<ClassModel> addRandomClassFull() {
return Mono.zip(
//request teacher microservice and return Mono - single teacher
reactiveNetClient.addRandomTeacher(),
//request students microservice and return Flux - list of students
reactiveNetClient.addRandomStudents(10),
(teacher, students) -> {
ClassModel classModel = new ClassModel();
classModel.setRoomNr("24B");
classModel.setClassName(faker.educator().course());
classModel.setTeacherId(teacher.getId());
students.forEach(student -> classModel.addStudentId(student.getId());
return classModel;
}).flatMap(classRepository::save);
}
Obviously, the controller is wrong as: 显然,控制器是错误的:
1) Mono.zip()
takes 2 or more Mono's, where I have Mono and Flux - How to combine them? 1)
Mono.zip()
需要2个或多个Mono,其中我有Mono和Mono.zip()
如何将它们组合?
2) Also not sure if: 2)也不确定是否:
students.forEach(student -> classModel.addStudentId(student.getId());
is right aproach? 是正确的方法吗?
Any suggestions, please? 有什么建议吗?
addRandomStudents()
to return Mono<List<Student>>
addRandomStudents()
以返回Mono<List<Student>>
You can use collectList()
on Flux<Student>
, it will return then Mono<List<Student>>
and then in addStudents()
will convert Student
object to id. 您可以在
Flux<Student>
上使用collectList()
,它将返回,然后Mono<List<Student>>
,然后在addStudents()
中将Student
对象转换为id。
public Mono<ClassModel> addRandomClassFull() { return Mono.zip( reactiveNetClient.addRandomTeacher(), reactiveNetClient.addRandomStudents(10).collectList(), (teacher, students) -> { ClassModel classModel = new ClassModel(); classModel.setRoomNr("24B"); classModel.setClassName(faker.educator().course()); classModel.setTeacherId(teacher.getId()); classModel.addStudents(students); return classModel; }).flatMap(classRepository::save); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.