- for (int i = 0; running; i++)
- {
- String message = "Message #" + i;
- for (ChatRoomInfoTo chatRoom : chatRooms)
- {
- sendMessage(chatRoom, message)
- .retryWhen(Retry.fixedDelay(10, Duration.ofSeconds(1)))
- .map(MessageTo::toString)
- .onErrorResume(throwable ->
- {
- WebClientResponseException e = (WebClientResponseException)throwable.getCause();
- return Mono.just(e.getResponseBodyAsString(Charset.defaultCharset()));
- })
- .subscribe(result -> log.info(
- "{} sent a message to {}: {}",
- user,
- chatRoom,
- result));
- }
- try
- {
- Thread.sleep(ThreadLocalRandom.current().nextLong(700, 1000));
- }
- catch (Exception e)
- {
- throw new RuntimeException(e);
- }
- }
+ return Flux
+ .fromIterable((Iterable<Integer>) () -> new Iterator<>()
+ {
+ private int i = 0;
+
+ @Override
+ public boolean hasNext()
+ {
+ return running;
+ }
+
+ @Override
+ public Integer next()
+ {
+ return i++;
+ }
+ })
+ .delayElements(Duration.ofMillis(ThreadLocalRandom.current().nextLong(500, 1500)))
+ .map(i -> "Message #" + i)
+ .flatMap(message -> sendMessage(chatRoom, message)
+ .retryWhen(Retry.backoff(10, Duration.ofSeconds(1))))
+ .doOnNext(message ->
+ {
+ sentMessages.add(message);
+ log.info(
+ "{} sent a message to {}: {}",
+ user,
+ chatRoom,
+ message);
+ })
+ .doOnError(throwable ->
+ {
+ WebClientResponseException e = (WebClientResponseException)throwable.getCause();
+ log.error(
+ "{} failed sending a message: {}",
+ user,
+ e.getResponseBodyAsString(Charset.defaultCharset()));
+ })
+ .limitRate(1)
+ .takeUntil(message -> !running)
+ .doOnComplete(() -> log.info("TestWriter {} is done", user))
+ .parallel(1)
+ .runOn(Schedulers.parallel())
+ .then();