【问题标题】:How to get username from mono<user> on spring boot webflux?如何在 spring boot webflux 上从 mono<user> 获取用户名?
【发布时间】:2019-11-11 19:27:17
【问题描述】:

我尝试制作 Spring Boot webflux 的处理程序和路由器类。模型类是用户类。代码是

@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 项目的处理程序类。在注册方法中,我制作了 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 字符串。 将需要任何 cmets。我被这部分卡住了。

【问题讨论】:

    标签: java spring-boot reactive-programming spring-webflux


    【解决方案1】:

    这里的错误之一是String id = monoUser.map(u -&gt; u.get_id()).toString();。 toString 将返回一个类似“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());
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      一种更简洁的方法是(我不喜欢其他人在地图中返回 null)是使用doOnSuccess

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

      我省略了任何错误检查,但它们应该正确完成。

      【讨论】:

        猜你喜欢
        • 2021-01-20
        • 2020-11-22
        • 2020-04-30
        • 1970-01-01
        • 2015-04-15
        • 2018-08-23
        • 2020-12-26
        • 2018-09-06
        • 2019-12-14
        相关资源
        最近更新 更多