webflux 小例子
Mono使用
// 根据id查询 public Mono<ServerResponse> getUserById(ServerRequest request) { Integer id = Integer.valueOf(request.pathVariable("id")); // 非空处理 Mono<ServerResponse> notFound = ServerResponse.notFound().build(); Mono<User> userMono = this.userService.getUserById(id); //把userMono 进行转换 //使用Reactor 操作符flatMap return userMono .flatMap(user -> ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromValue(user))) .switchIfEmpty(notFound); }
doOnNext, thenEmpty
@Override public Mono<Void> saveUserInfo(Mono<User> userMono) { return userMono.doOnNext(user -> { // 放到Map this.users.put(user.getId(), user); }).thenEmpty(Mono.empty());// 终止信号 } @Override public Flux<User> getAllUser() { return Flux.fromIterable(this.users.values()); }