![](/img/trans.png)
[英]How to use Mono and Flux in handler functions with Spring WebFlux Reactive ways
[英]webflux how to pass current login Mono string to a flux
我還是 Spring Boot Webflux 的新手。 我使用 Casssandra 作為我的數據庫,下面我有一個朋友表,我想根據我的登錄 ID 獲取我所有的朋友。 如何獲取當前登錄 ID 並將 ID 傳遞給通量
// Here i retrieved currently login user ID which is a mono string
public Mono<String> getUserID(Mono<String> principal) {
return principal
.map(Principal::getName)
}
或者
public static Mono<String> getUserIDFromRequest(ServerRequest request) {
return request.principal()
.cast(UsernamePasswordAuthenticationToken.class)
.map(UsernamePasswordAuthenticationToken::getName);
}
// My friends table
public class Friends {
@PrimaryKey("userid")
private long userId;
private long friendId;
private FriendObject friendObject;
private String since;
private boolean enableNotifications;
private boolean allowMessages;
// Getters and setters
}
@Repository
public interface FriendsRepository extends ReactiveCassandraRepository<Friends, Long> {
}
@Service
public class FriendshipServiceImpl implements FriendshipService {
@Override
public Mono<Friends> addFriend(Friends friends) {
return friendsRepository.save(friends);
}
}
public class FriendshipHandler {
// How to pass the Login Mono<String> to this flux Or how can i combine Mono and Flux?
@GetMapping(path="/friends/list", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<Friends> getFriends(Mono<Principal> principal) {
return friendshipService.getFriends(Long.valueOf("The login ID"));
}
OR
public Mono<ServerResponse> getFriends(ServerRequest request) {
return ok().body(
friendshipService
.getFriends(Long.valueOf("The login ID")), Friends.class);
}
}
這是基本的 webflux 所以如果你不能這樣做,你需要閱讀
@GetMapping(path="/friends", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<Friends> getFriends(Mono<Principal> principal) {
return principal.map(principal -> {
return // Here you do what you need to with the principal
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.