Spring Boot 4 Microservices & REST APIs · Урок

Проверки работоспособности и метрики

Реализуйте Spring Boot Actuator для предоставления конечных точек проверки работоспособности и сбора метрик приложения.

Урок 2 из 312 шагов

«Проверки работоспособности и метрики» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 2 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 3 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What is Spring Boot Actuator?

When running microservices, monitoring their health and performance is super important. Spring Boot Actuator provides a set of production-ready features to help you do just that!

It exposes operational information about your running application, making it easier to observe and manage.

Add Actuator Dependency

To start using Actuator, you just need to add its dependency to your Spring Boot project. This is typically done in your pom.xml for Maven or build.gradle for Gradle.

Here's how to add it with Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Explore Default Endpoints

Once the Actuator dependency is added, Spring Boot automatically configures several useful endpoints. These endpoints provide valuable insights into your application's state.

  • /actuator/health: Shows the application's health status.
  • /actuator/info: Displays general application information.
  • /actuator/metrics: Provides detailed metrics data.

Checking Application Health

The /actuator/health endpoint is a fundamental part of monitoring. It tells you if your application and its integrated components (like databases or disk space) are functioning correctly.

A simple "UP" status means everything is good! Run this basic app and check its health endpoint.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ActuatorDemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(ActuatorDemoApplication.class, args);
  }
}

Accessing Health Endpoint

After running the previous application, open your browser and navigate to http://localhost:8080/actuator/health.

You should see a JSON response indicating the application's overall status, typically {"status":"UP"}.

This is a quick way to verify if your service is alive!

Create Custom Health Checks

You can extend Actuator's health checks to include your own custom logic. For example, checking the status of an external API, a message queue, or a specific business process.

To do this, you implement the HealthIndicator interface:

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

@Component
public class CustomServiceHealthIndicator implements HealthIndicator {
  private final String SERVICE_NAME = "MyExternalService";

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

  private boolean isServiceUp() {
    // Simulate checking an external service
    return Math.random() > 0.3; // 70% chance of being up
  }
}

Understanding Application Metrics

Metrics are numerical data points that describe your application's behavior over time. They are crucial for understanding performance, resource usage, and identifying potential bottlenecks.

Spring Boot Actuator, powered by Micrometer, automatically collects various metrics:

  • CPU and memory usage
  • HTTP request counts and latencies
  • Database connection pool statistics

Querying Metrics Data

The /actuator/metrics endpoint provides a list of all available metrics. You can then query specific metrics for detailed information.

  • Visit http://localhost:8080/actuator/metrics to see available metrics.
  • Then, try http://localhost:8080/actuator/metrics/jvm.memory.used to see the specific memory usage metric.

This allows you to gather precise data for monitoring dashboards.

Implement Custom Metrics

Beyond the default metrics, you can track application-specific events using custom metrics. Micrometer provides simple APIs for different metric types like Counters, Gauges, and Timers.

Here's an example of a custom Counter:

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Service;

@Service
public class MyService {
  private final Counter customCounter;

  public MyService(MeterRegistry meterRegistry) {
    this.customCounter = Counter.builder("my_app.processed.items")
                                .description("Number of items processed by MyService")
                                .register(meterRegistry);
  }

  public void processItem() {
    System.out.println("Processing an item...");
    customCounter.increment(); // Increment the counter
  }
}

Customize Endpoint Exposure

By default, only /health and /info are typically exposed over HTTP. You can configure which other endpoints Actuator makes available using application.properties or application.yml.

To expose more endpoints like metrics, beans, and env, add this line:

management.endpoints.web.exposure.include=health,info,metrics,beans,env

Actuator Knowledge Check

Let's quickly check your understanding of Spring Boot Actuator's benefits.

Lesson Recap

Great job! In this lesson, you learned about:

  • Spring Boot Actuator for monitoring and managing microservices.
  • Implementing health checks using the /actuator/health endpoint.
  • Creating custom health indicators for specific services.
  • Understanding and collecting application metrics via /actuator/metrics.
  • Implementing custom metrics with Micrometer.
  • The importance of securing Actuator endpoints in production.

Next, we'll dive into centralized logging and dashboarding!

Можно начать бесплатно

Изучай Java с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
24
Уроки
93

Часто задаваемые вопросы

Урок «Проверки работоспособности и метрики» бесплатный?

Да — полный текст урока «Проверки работоспособности и метрики» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 3 уроков всего.

Чему я научусь в уроке «Проверки работоспособности и метрики»?

Реализуйте Spring Boot Actuator для предоставления конечных точек проверки работоспособности и сбора метрик приложения. Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 3.

Сколько времени занимает урок «Проверки работоспособности и метрики»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Централизованное журналирование со стеком ELK
  2. Проверки работоспособности и метрики
  3. Оповещения и информационные панели
← Назад к Spring Boot 4 Microservices & REST APIs