[英]How to get username from mono<user> on spring boot webflux?
I try to make handler and router classes of spring boot webflux. 我尝试制作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;
}
And below is the handler class of webflux project. 下面是webflux项目的处理程序类。 In register method, I make the id duplication test codes.
在注册方法中,我制作id重复测试代码。 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();
}
}
I want to extract the username or id string from Mono of spring webflux. 我想从spring webflux的Mono中提取用户名或ID字符串。 Any comments will be needed.
任何评论都是需要的。 I am stuck with this part.
我坚持这一部分。
One of the things which is wrong here is this like String id = monoUser.map(u -> u.get_id()).toString();
这是错误的事情之一,例如
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.
toString将返回一个类似于“ Mono @ 13254216541”的字符串,因为您正在调用Mono.toString。
One more thing, you shouldn't use the request's data in the body of your function, but in a map or flatMap function. 还有一件事,您不应在函数主体中使用请求的数据,而应在map或flatMap函数中使用。
You could replace it by something like (I'm doing it by head so it might not be 100% syntax corect): 您可以将其替换为类似的内容(我正在脑海中做,因此它可能不是100%语法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());
Hope this helps! 希望这可以帮助!
a more clean approach would be (i don't like the return of null in the map that others have done) is use the doOnSuccess
: 一种更干净的方法是(我不喜欢其他人在地图中返回null)是使用
doOnSuccess
:
request.bodyToMono(User.class)
.doOnSuccess(user -> return userRepository.insert(user))
.map(user -> ServerResponse.ok(user))
i have left out any error checks but ofc they should be done properly. 我没有进行任何错误检查,但ofc应该正确进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.