0Pricing
Spring Boot 4 Complete Guide · レッスン

ヘルスチェックとレジリエンスパターン

堅牢なヘルスチェックを設計し、サーキットブレーカーなどのレジリエンスパターンを適用して、障害耐性のあるシステムを構築します。

「ヘルスチェックとレジリエンスパターン」はCoddyKit上の無料Spring Boot 4 Complete Guideレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Complete Guide学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Introduction to Health Checks

In production, applications need to be robust. Health checks are automated ways to verify if an application or service is running correctly and ready to receive traffic.

  • They tell orchestrators (like Kubernetes) if your app is alive.
  • They prevent traffic from being sent to unhealthy instances.
  • They help in automatic recovery and scaling decisions.

Spring Boot Actuator Health

Spring Boot Actuator provides a built-in /actuator/health endpoint. By default, it aggregates health information from various components like databases, disk space, and more.

When accessed, it returns a status, typically UP or DOWN, along with details about included components.

Accessing Health Endpoint

To see the health status, you just need to enable Actuator and access the endpoint. Here's how you might configure it in application.properties:

management.endpoints.web.exposure.include=health
management.endpoint.health.show-details=always

Custom Health Indicators

Sometimes, the default health checks aren't enough. You might have an external API, a custom cache, or a specific business logic that needs monitoring.

You can create custom health indicators by implementing the HealthIndicator interface to add your own checks to the /actuator/health endpoint.

Implementing a Custom Indicator

Let's create a simple custom health indicator for a hypothetical external service. If the service is 'available', it reports UP; otherwise, DOWN.

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;

@Component
public class ExternalServiceHealthIndicator implements HealthIndicator {

    private final String SERVICE_NAME = "MyExternalService";

    @Override
    public Health health() {
        if (isExternalServiceUp()) {
            return Health.up().withDetail(SERVICE_NAME, "Available").build();
        } else {
            return Health.down().withDetail(SERVICE_NAME, "Not Available").build();
        }
    }

    private boolean isExternalServiceUp() {
        // Simulate checking external service status
        // In a real app, this would involve network calls, DB queries, etc.
        return Math.random() > 0.3; // 70% chance of being up
    }

    public static void main(String[] args) {
        ExternalServiceHealthIndicator indicator = new ExternalServiceHealthIndicator();
        System.out.println("Service Health: " + indicator.health().getStatus());
    }
}

Liveness vs. Readiness Probes

When deploying to container orchestrators like Kubernetes, two types of probes are crucial:

  • Liveness Probe: Determines if an application instance is running. If it fails, Kubernetes restarts the container.
  • Readiness Probe: Determines if an application instance is ready to serve traffic. If it fails, Kubernetes stops sending traffic to it.

Spring Boot 2.3+ introduced distinct health groups for these, often mapped to /actuator/health/liveness and /actuator/health/readiness.

Introduction to Resilience

Even with health checks, external dependencies can fail, causing your application to crash or slow down. Resilience patterns help your application gracefully handle failures and continue operating under adverse conditions.

  • They improve fault tolerance and stability.
  • They prevent cascading failures across services.
  • They ensure a better user experience even when parts of the system are struggling.

The Circuit Breaker Pattern

The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that is likely to fail. It's like an electrical circuit breaker: if too much current flows, it trips to prevent damage.

  • CLOSED: Requests pass through. If failures exceed a threshold, it trips to OPEN.
  • OPEN: Requests immediately fail (fast-fail). After a timeout, it transitions to HALF_OPEN.
  • HALF_OPEN: A limited number of test requests are allowed. If they succeed, it closes; otherwise, it opens again.

Circuit Breaker with Resilience4j

Resilience4j is a popular library for implementing resilience patterns. Here's a simplified example of a circuit breaker protecting a slow method call.

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import java.time.Duration;

public class CircuitBreakerDemo {

    private final CircuitBreaker circuitBreaker;

    public CircuitBreakerDemo() {
        CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(50) // 50% failure rate to open
            .waitDurationInOpenState(Duration.ofSeconds(5)) // 5s before HALF_OPEN
            .ringBufferSizeInHalfOpenState(2) // 2 calls in HALF_OPEN
            .ringBufferSizeInClosedState(5) // 5 calls in CLOSED for failure rate calc
            .build();

        CircuitBreakerRegistry circuitBreakerRegistry = 
            CircuitBreakerRegistry.of(circuitBreakerConfig);
        circuitBreaker = circuitBreakerRegistry.circuitBreaker("myService");
    }

    public String callExternalService() {
        return circuitBreaker.executeSupplier(() -> {
            if (Math.random() < 0.6) { // Simulate 60% failure rate
                throw new RuntimeException("Service failed!");
            }
            return "Service Data";
        });
    }

    public static void main(String[] args) {
        CircuitBreakerDemo demo = new CircuitBreakerDemo();
        for (int i = 0; i < 15; i++) {
            try {
                System.out.println(i + ": " + demo.callExternalService());
            } catch (Exception e) {
                System.err.println(i + ": Error - " + e.getMessage() + 
                                   " | CB State: " + demo.circuitBreaker.getState());
                try { Thread.sleep(500); } catch (InterruptedException ie) {}
            }
        }
    }
}

Fallback Methods

When a circuit breaker is open or a service call fails, you don't always want to just throw an error. A fallback method provides an alternative response or action when the primary operation fails.

This allows your application to degrade gracefully, perhaps by returning cached data, a default response, or an empty list, instead of crashing or showing a full error page.

Quick Check on Resilience

Which of the following are benefits of implementing resilience patterns like the Circuit Breaker?

Recap: Health & Resilience

We've explored how health checks, particularly with Spring Boot Actuator and custom indicators, help monitor application status and readiness for traffic.

We also learned about resilience patterns, focusing on the Circuit Breaker, to prevent cascading failures and ensure graceful degradation when external services or components fail. Implementing these patterns is key for building robust, production-ready microservices.

よくある質問

「ヘルスチェックとレジリエンスパターン」レッスンは無料ですか?

はい。「ヘルスチェックとレジリエンスパターン」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Complete Guideコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。

「ヘルスチェックとレジリエンスパターン」で何を学びますか?

堅牢なヘルスチェックを設計し、サーキットブレーカーなどのレジリエンスパターンを適用して、障害耐性のあるシステムを構築します。 ブラウザで直接実行するハンズオンコードでSpring Boot 4 Complete Guideを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Spring Boot 4 Complete Guideを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSpring Boot 4 Complete Guideは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「ヘルスチェックとレジリエンスパターン」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSpring Boot 4 Complete Guideレッスンでコードを書いて実行できますか?

はい。すべてのSpring Boot 4 Complete Guideレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Kubernetesオーケストレーションの基礎
  2. SleuthとZipkinによる分散トレーシング
  3. ヘルスチェックとレジリエンスパターン
  4. MicrometerとPrometheusによるメトリクスとダッシュボード
← Spring Boot 4 Complete Guideに戻る