健康检查与指标
实现 Spring Boot Actuator,公开健康检查端点并收集应用指标。
健康检查与指标 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 2 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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/metricsto see available metrics. - Then, try
http://localhost:8080/actuator/metrics/jvm.memory.usedto 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,envActuator 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/healthendpoint. - 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!
常见问题解答
「健康检查与指标」课时是免费的吗?
是的 — 「健康检查与指标」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 3 节课。
「健康检查与指标」这节课中我会学到什么?
实现 Spring Boot Actuator,公开健康检查端点并收集应用指标。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 3 节。
「健康检查与指标」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?
能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 ELK Stack 集中式日志记录
- 健康检查与指标
- 告警与监控面板