Spring WebFlux - 将 Flux 转换为 List<Object>

Aja*_*mar 10 spring h2 spring-webflux r2dbc

我正在学习 Spring WebFlux。

我的实体是这样的:

@Table("users")
public class User {
    @Id
    private Integer id;
    private String name;
    private int age;
    private double salary;
}
Run Code Online (Sandbox Code Playgroud)

我有一个存储库(R2 使用 H2 数据库),如下所示:

public interface UserRepository extends ReactiveCrudRepository<User,Integer> {
   
}
Run Code Online (Sandbox Code Playgroud)

我的控制器是:

    @Autowired
    private UserRepository userRepository;

    private static List<User> userList = new ArrayList<>();

    @PostConstruct
    public void initializeStockObjects() {
        User stock1 = new User(11, "aaaa", 123, 123);
        User stock2 = new User(12, "bbb", 123, 123);
        User stock3 = new User(13, "ccc", 123, 123);
        userList.add(stock1);
        userList.add(stock2);
        userList.add(stock3);
    }

    @RequestMapping(value = "/livelistofusers", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<List<User>> getUsers() {
        return getUserData(userList);
    }

    public Flux<List<User>> getUserData(List<User> userList) {
       Flux<Long> interval = Flux.interval(Duration.ofSeconds(3));
       interval.subscribe((i) -> userList.forEach(user -> addNewUser(user)));
       Flux<List<User>> transactionFlux = Flux.fromStream(Stream.generate(() -> userList));
       return Flux.zip(interval, transactionFlux).map(Tuple2::getT2);
     }
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好。我能够每 3 秒将整个用户列表返回到视图中。这里完全没有问题。

现在,我想将 Flue 即 Flux Flux2 = userRepository.findAll() 发送到视图。这意味着,而不是return getUserData(userList);我该怎么办 return getUserData(flux2(...what should I do here ???... I tried couple of things but I end up making the Blocking list instead of Non-Blocking ...));

问题:我怎样才能实现这一目标?即我如何每 3 秒将整个 Flux 发送到我的视图中。我在这里感到迷失,毫无头绪。任何相关的帮助链接或解决方案将不胜感激。

编辑:

根据 Nipuna 的评论,我尝试了以下操作:

@RequestMapping(value = "/livelistofusersall", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<List<User>>  getUsersall() {
        Flux<Long> interval = Flux.interval(Duration.ofSeconds(3));
        interval.subscribe((i) -> userRepository.findAll());
        Flux<List<User>> transactionFlux = userRepository.findAll().collectList().flatMapMany(Flux::just);
        return Flux.zip(interval, transactionFlux).map(Tuple2::getT2);
    }
Run Code Online (Sandbox Code Playgroud)

但现在在我的上下文路径中,列表在等待 3 秒后“仅加载一次”。我在这里缺少什么?

Nip*_*nga 16

您可以使用collectList()Flux 中的运算符来实现此目的,它给出了 Mono 列表。

userRepository.findAll().collectList().flatMapMany(Flux::just);
Run Code Online (Sandbox Code Playgroud)