Reputation: 11
I need to send webhooks to a specific URL and, if unsuccessful, repeat the sending several times, and save the response status, response body, and attempt number for each request at database.
I wrote two methods:
@SneakyThrows
public void sendWebHook(Transaction transaction) {
RetryBackoffSpec retryBackoffSpec = Retry.fixedDelay(5, Duration.ofSeconds(10));
GetTransactionResponse requestBody = transactionMapper.transactionToGetResponse(transaction);
webClient.post()
.uri(transaction.getNotificationUrl())
.body(Mono.just(requestBody), GetTransactionResponse.class)
.retrieve()
.onStatus(HttpStatusCode::isError, response ->
response
.toEntity(WebhookResponse.class)
.flatMap(responseEntity -> {
saveWebhook(transaction, responseEntity);
return Mono.error(new SendWebhookException(Objects.requireNonNull(responseEntity.getBody()).message(), "WEB_CLIENT_ERROR"));
}
)
)
.toEntity(WebhookResponse.class)
.timeout(Duration.ofSeconds(5))
.retryWhen(retryBackoffSpec)
.doOnSuccess(responseEntity -> saveWebhook(transaction, responseEntity))
.subscribe();
}
@SneakyThrows
private void saveWebhook(Transaction transaction, ResponseEntity<WebhookResponse> responseEntity) {
Json jsonRequestBody = Json.of(objectMapper.writeValueAsString(transactionMapper.transactionToGetResponse(transaction)));
Json jsonResponseBody = Json.of(objectMapper.writeValueAsString(responseEntity.getBody()));
WebHook webHook = WebHook.builder()
.transactionId(transaction.getId())
.attemptNumber(1)
.requestBody(jsonRequestBody)
.transaction(transaction)
.responseStatus(responseEntity.getStatusCode().value())
.responseBody(jsonResponseBody)
.createdAt(LocalDateTime.now())
.build();
webHookRepository.save(webHook).subscribe();
}
How can i get number of retry attempt?
Upvotes: 1
Views: 34