我还是Spring Boot Webflux的新手。我使用Casssandra作为数据库,下面有一个friends表,我想根据我的登录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
});
}