1 package de.juplo.kafka.chat.backend;
3 import de.juplo.kafka.chat.backend.api.ChatRoomInfoTo;
4 import de.juplo.kafka.chat.backend.api.MessageTo;
5 import lombok.extern.slf4j.Slf4j;
6 import org.springframework.http.HttpStatus;
7 import org.springframework.http.MediaType;
8 import org.springframework.web.reactive.function.client.WebClient;
9 import org.springframework.web.reactive.function.client.WebClientResponseException;
10 import reactor.core.publisher.Mono;
11 import reactor.util.retry.Retry;
13 import java.nio.charset.Charset;
14 import java.time.Duration;
15 import java.util.concurrent.ThreadLocalRandom;
19 public class TestWriter implements Runnable
24 for (int i = 0; running; i++)
26 String message = "Message #" + i;
29 sendMessage(chatRoom, message)
30 .retryWhen(Retry.fixedDelay(10, Duration.ofSeconds(1)))
31 .map(MessageTo::toString)
32 .onErrorResume(throwable ->
34 WebClientResponseException e = (WebClientResponseException)throwable.getCause();
35 return Mono.just(e.getResponseBodyAsString(Charset.defaultCharset()));
37 .subscribe(result -> log.info(
38 "{} sent a message to {}: {}",
43 Thread.sleep(ThreadLocalRandom.current().nextLong(700, 1000));
47 throw new RuntimeException(e);
52 private Mono<MessageTo> sendMessage(
53 ChatRoomInfoTo chatRoom,
59 "/{chatRoomId}/{username}/{serial}",
63 .contentType(MediaType.TEXT_PLAIN)
64 .accept(MediaType.APPLICATION_JSON)
66 .exchangeToMono(response ->
68 if (response.statusCode().equals(HttpStatus.OK))
70 return response.bodyToMono(MessageTo.class);
74 return response.createError();
80 private final WebClient webClient;
81 private final ChatRoomInfoTo chatRoom;
82 private final User user;
84 volatile boolean running = true;
87 TestWriter(Integer port, ChatRoomInfoTo chatRoom, String username)
89 webClient = WebClient.create("http://localhost:" + port);
90 this.chatRoom = chatRoom;
91 user = new User(username);