Example
1. Handling Payment Processing Failures
package org.example.service;
import org.example.client.PaymentGatewayClient;
import org.example.exception.PaymentException;
import org.example.exception.PaymentGatewayUnavailableException;
import org.example.model.PaymentRequest;
import org.example.model.PaymentResponse;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeoutException;
@Service
public class PaymentService {
private final PaymentGatewayClient paymentGatewayClient;
public PaymentService(PaymentGatewayClient paymentGatewayClient) {
this.paymentGatewayClient = paymentGatewayClient;
}
// Retryable method for processing payment
@Retryable(
retryFor = { TimeoutException.class, PaymentGatewayUnavailableException.class },
maxAttempts = 5,
backoff = @Backoff(delay = 2000, multiplier = 2.0)
)
public PaymentResponse processPayment(PaymentRequest request) throws PaymentException {
// Call the third-party payment gateway
return paymentGatewayClient.processPayment(request);
}
// Recovery method if retries fail
@Recover
public PaymentResponse recover(PaymentGatewayUnavailableException e, PaymentRequest request) {
System.out.println("Recovering after retries failed for request: " + request.getTransactionId());
// Mark transaction as pending and notify user to retry
return markTransactionAsPending(request);
}
private PaymentResponse markTransactionAsPending(PaymentRequest request) {
// Logic to mark the transaction as pending due to payment failures
return new PaymentResponse("PENDING", "Your payment is pending. Please try again later.");
}
}Last updated