如何在 spring boot webflux 上从 mono<user> 获取用户名?

How to get username from mono<user> on spring boot webflux?

我尝试使 spring 的处理程序和路由器 classes 引导 webflux。模型 class 是用户 class。代码是

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Document(collection="Users") 
public class User {

    @Id 
    private String _id;

    @Indexed(unique = true) 
    private Long id; 

    @Indexed(unique=true)  
    private String username;

    private String password;

    private String email;

    private String fullname;

    private String role;
}

下面是 webflux 项目的处理程序 class。在 register 方法中,我制作了 id 重复测试代码。但这是完全错误的。

@Component
public class UserHandler {

    @Autowired
    private UserReactiveMongoRepository userRepository;

    public Mono<ServerResponse> register(ServerRequest request) {
        Mono<User> monoUser = request.bodyToMono(User.class);
        String id = monoUser.map(u -> u.get_id()).toString();

        if(userRepository.existsById(id) == null)
            return ServerResponse.ok().build(userRepository.insert(monoUser));

        return ServerResponse.ok().build();
    }
}

我想从 spring webflux 的 Mono 中提取用户名或 ID 字符串。 需要任何意见。我被这部分卡住了。

这里的错误之一是 String id = monoUser.map(u -> u.get_id()).toString();。 toString 将 return 你一个像 "Mono@13254216541" 这样的字符串,因为你正在调用 Mono.toString.

还有一点,您不应该在函数体中使用请求的数据,而应该在 map 或 flatMap 函数中使用。

你可以用类似的东西替换它(我是用头来做的,所以它可能不是 100% 语法正确):

Mono<User> userMono = request.bodyToMono(User.class);//Create a Mono<User>

userMono.map((user) -> { //In the map method, we access to the User object directly
  if(user != null && user.getId() != null){
    return userRepository.insert(user); // Insert User instead of Mono<User> in your repository
  }
  return null;
}) //This is still a Mono<User>
.map(insertedUser -> ServerResponse.ok(insertedUser)) //This is a Mono<ServerResponse>
.switchIfEmpty(ServerResponse.ok());

希望对您有所帮助!

更干净的方法是(我不喜欢其他人所做的地图中的 return 为空)是使用 doOnSuccess:

request.bodyToMono(User.class)
    .doOnSuccess(user -> return userRepository.insert(user))
    .map(user -> ServerResponse.ok(user))

我遗漏了任何错误检查,但他们应该正确完成。