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 TestClient implements Runnable
24 for (int i = 0; running; i++)
26 String message = "Message #" + i;
27 for (ChatRoomInfoTo chatRoom : chatRooms)
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 {}: {}",
45 Thread.sleep(ThreadLocalRandom.current().nextLong(700, 1000));
49 throw new RuntimeException(e);
54 private Mono<MessageTo> sendMessage(
55 ChatRoomInfoTo chatRoom,
61 "/{chatRoomId}/{username}/{serial}",
65 .contentType(MediaType.TEXT_PLAIN)
66 .accept(MediaType.APPLICATION_JSON)
68 .exchangeToMono(response ->
70 if (response.statusCode().equals(HttpStatus.OK))
72 return response.bodyToMono(MessageTo.class);
76 return response.createError();
82 private final WebClient webClient;
83 private final ChatRoomInfoTo[] chatRooms;
84 private final User user;
86 volatile boolean running = true;
89 TestClient(Integer port, ChatRoomInfoTo[] chatRooms, String username)
91 webClient = WebClient.create("http://localhost:" + port);
92 this.chatRooms = chatRooms;
93 user = new User(username);