7 Advanced Spring Boot Cases: Resilience4j, Actuator, Cache & More
This article presents seven advanced Spring Boot topics—including Resilience4j circuit breaking, custom Actuator health checks, Saga-based distributed transactions, cache optimization, asynchronous processing, Gateway vs. Zuul, and OAuth2/JWT security—each illustrated with concise explanations, implementation steps, and code samples.
1. Introduction
Spring Boot’s simplicity often hides its powerful capabilities for handling complex enterprise requirements. This article briefly introduces seven advanced Spring Boot topics and reinforces basic understanding with short explanations and examples.
2. Practical Cases
2.1 Implement Resilience4j for Resilient Microservices
Microservices need to handle transient failures gracefully. Resilience4j integrates with Spring Boot to provide patterns such as Circuit Breaker, Retry, and Rate Limiter.
<code>@Resource
@LoadBalanced
private RestTemplate restTemplate;
@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public String getUserDetails(String userId) {
return restTemplate.getForObject("http://user-service/users/" + userId, String.class);
}
public String fallback(String userId, Throwable ex) {
return String.format("Failed to get user [%s], %s", userId, ex.getMessage());
}
</code>Implementation steps:
Add the Resilience4j Spring Boot starter dependency.
Configure circuit‑breaker properties (e.g., failure‑rate‑threshold, sliding‑window‑size, wait‑duration‑in‑open‑state).
<code>resilience4j:
circuitbreaker:
instances:
userService:
failure-rate-threshold: 60
sliding-window-type: count-based
sliding-window-size: 3
minimum-number-of-calls: 3
wait-duration-in-open-state: 10000
</code>2.2 Custom Monitoring with Spring Boot Actuator
Actuator exposes endpoints for metrics, health checks, etc. By defining a custom HealthIndicator , you can monitor application‑specific metrics.
<code>@Component
public class PackHealthIndicator implements HealthIndicator {
@Override
public Health health() {
boolean isHealthy = checkCustomHealth();
return isHealthy ? Health.up().build()
: Health.down().withDetail("Error", "Custom check failed").build();
}
private boolean checkCustomHealth() {
// custom health‑check logic
return true;
}
}
</code>Implementation steps:
Define a bean that implements HealthIndicator .
Implement the custom health‑check logic.
Access the health endpoint (e.g., /actuator/health ).
2.3 Distributed Transaction Handling (Saga)
Managing transactions across multiple services can be tackled with patterns like 2PC, TCC, or Saga. Below is a simplified Saga example using Spring Boot and Kafka.
<code>@KafkaListener(topics = "order-events")
public void processOrder(OrderEvent event) {
if ("ORDER_CREATED".equals(event.getStatus())) {
// handle payment and inventory
}
}
</code>The payment service publishes success or failure events based on processing results. Saga ensures eventual consistency through event‑driven workflows, and frameworks such as Axon can simplify implementation.
2.4 Performance Optimization with Cache
Caching reduces database load and improves response times.
<code>@Cacheable(value = "users", key = "#userId")
public User getUserById(String userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(userId));
}
</code>Implementation steps:
Add cache starter dependencies (e.g., spring-boot-starter-cache , optionally spring-boot-starter-data-redis for Redis).
Use annotations such as @Cacheable , @CacheEvict , and @CachePut on methods.
2.5 Simplify Asynchronous Programming
The @Async annotation makes asynchronous execution straightforward.
<code>@Service
public class EmailService {
@Async
public void sendEmail(String email, String message) throws InterruptedException {
Thread.sleep(3000); // simulate delay
System.out.printf("Sending email to: %s%n", email);
}
}
@EnableAsync
@Configuration
public class AsyncConfig {}
</code>Enabling @EnableAsync is essential for the async infrastructure to work.
2.6 Gateway vs. Zuul
Spring Cloud Gateway is a reactive API gateway that replaces Netflix Zuul, offering better performance and flexibility.
<code>@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("user_route", r -> r.path("/users/**")
.uri("http://user-service"))
.build();
}
</code>Key features include routing & filtering, integration with Resilience4j circuit breakers, WebSocket support, and load balancing.
2.7 Protect Applications with OAuth2 or JWT
OAuth2 and JWT are commonly used to secure APIs.
<code>public String generateToken(UserDetails userDetails) {
return Jwts.builder()
.setSubject(userDetails.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(SignatureAlgorithm.HS512, "xxxooo")
.compact();
}
public boolean validateToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey("xxxooo")
.parseClaimsJws(token)
.getBody();
return claims.getExpiration().after(new Date());
}
</code>A custom AuthenticationFilter validates the token and populates the security context. Security configuration disables CSRF, requires authentication for all requests, enables HTTP Basic (optional), sets stateless session management, and registers the custom filter before UsernamePasswordAuthenticationFilter .
<code>@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(reg -> reg.requestMatchers("/**").authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
</code>These steps complete a basic JWT‑based API security setup.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.