java
36 lines · 7 steps
Resilient payment calls in Spring
A Spring service wraps an HTTP call to a payment gateway with retries, a circuit breaker, and typed fallbacks.
Explained by
highlit
1@Service
2public class PaymentGatewayClient {
3
4 private static final Logger log = LoggerFactory.getLogger(PaymentGatewayClient.class);
5
6 private final RestClient restClient;
7
8 public PaymentGatewayClient(RestClient.Builder builder,
9 @Value("${payment.gateway.base-url}") String baseUrl) {
10 this.restClient = builder.baseUrl(baseUrl).build();
11 }
12
13 @CircuitBreaker(name = "paymentGateway", fallbackMethod = "chargeFallback")
14 @Retry(name = "paymentGateway")
15 public ChargeResult charge(ChargeRequest request) {
16 return restClient.post()
17 .uri("/v1/charges")
18 .contentType(MediaType.APPLICATION_JSON)
19 .body(request)
20 .retrieve()
21 .onStatus(HttpStatusCode::is5xxServerError, (req, res) -> {
22 throw new PaymentGatewayException("Gateway returned " + res.getStatusCode());
23 })
24 .body(ChargeResult.class);
25 }
26
27 private ChargeResult chargeFallback(ChargeRequest request, CallNotPermittedException ex) {
28 log.warn("Circuit open for paymentGateway, rejecting charge for order {}", request.orderId());
29 return ChargeResult.deferred(request.orderId());
30 }
31
32 private ChargeResult chargeFallback(ChargeRequest request, Throwable ex) {
33 log.error("Payment charge failed for order {}: {}", request.orderId(), ex.getMessage());
34 return ChargeResult.failed(request.orderId(), ex.getMessage());
35 }
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Resilience4j annotations let you add retries and a circuit breaker declaratively without cluttering the happy-path logic.
- 2Distinct fallback overloads matched by exception type let you react differently to an open circuit versus a genuine failure.
- 3Mapping 5xx responses to a custom exception turns transport errors into signals the resilience layer can act on.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/resilient-payment-calls-in-spring-explained-java-4a55/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.