如何从 mono<user> 获取用户名在 spring 引导 webflux 上? [英] How to get username from mono&lt;user&gt; on spring boot webflux?

查看:193
本文介绍了如何从 mono<user> 获取用户名在 spring 引导 webflux 上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试制作 spring boot webflux 的处理程序和路由器类.模型类是用户类.代码是

I try to make handler and router classes of spring boot webflux. The model class is user class. Codes are

@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重复测试代码.但这是完全错误的.

And below is the handler class of webflux project. In register method, I make the id duplication test codes. But It is totally WRONG.

@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 字符串.将需要任何评论.我被这部分卡住了.

I want to extract the username or id string from Mono of spring webflux. Any comments will be needed. I am stuck with this part.

推荐答案

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

One of the things which is wrong here is this like String id = monoUser.map(u -> u.get_id()).toString();. The toString will return you a String like "Mono@13254216541", because you are calling Mono.toString.

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

One more thing, you shouldn't use the request's data in the body of your function, but in a map or flatMap function.

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

You could replace it by something like (I'm doing it by head so it might not be 100% syntax corect):

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());

希望这会有所帮助!

这篇关于如何从 mono<user> 获取用户名在 spring 引导 webflux 上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆