Actuator

Spring Boot 集成了 Spring Boot Actuator。本节回答了使用 Actuator 时经常遇到的问题。

更改 Actuator 端点的 HTTP 端口或地址

在独立应用中,Actuator 的 HTTP 端口默认与主 HTTP 端口相同。要使应用监听不同的端口,请设置外部属性:management.server.port。要在完全不同的网络地址上监听(例如,当您有用于管理的内部网络和用于用户应用的外部网络时),您还可以将 management.server.address 设置为服务器能够绑定的有效 IP 地址。

更多详细信息,请参阅 ManagementServerProperties 源代码以及“生产就绪特性”部分中的定制管理服务器端口

定制清理

要控制清理过程,请定义一个 SanitizingFunction bean。调用该函数时使用的 SanitizableData 提供了对键和值以及它们所属的 PropertySource 的访问权限。例如,这允许您清理来自特定属性源的每个值。每个 SanitizingFunction 会按顺序调用,直到某个函数更改了可清理数据的值。

将健康指示器映射到 Micrometer 度量

Spring Boot 健康指示器返回一个 Status 类型,以指示系统的整体健康状况。如果您想监控或对特定应用的健康水平进行预警,可以使用 Micrometer 将这些状态导出为度量。默认情况下,Spring Boot 使用状态码“UP”、“DOWN”、“OUT_OF_SERVICE”和“UNKNOWN”。要导出这些状态,您需要将这些状态转换为一组数字,以便与 Micrometer Gauge 一起使用。

以下示例展示了编写此类导出器的一种方法

  • Java

  • Kotlin

import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;

import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.health.Status;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
public class MyHealthMetricsExportConfiguration {

	public MyHealthMetricsExportConfiguration(MeterRegistry registry, HealthEndpoint healthEndpoint) {
		// This example presumes common tags (such as the app) are applied elsewhere
		Gauge.builder("health", healthEndpoint, this::getStatusCode).strongReference(true).register(registry);
	}

	private int getStatusCode(HealthEndpoint health) {
		Status status = health.health().getStatus();
		if (Status.UP.equals(status)) {
			return 3;
		}
		if (Status.OUT_OF_SERVICE.equals(status)) {
			return 2;
		}
		if (Status.DOWN.equals(status)) {
			return 1;
		}
		return 0;
	}

}
import io.micrometer.core.instrument.Gauge
import io.micrometer.core.instrument.MeterRegistry
import org.springframework.boot.actuate.health.HealthEndpoint
import org.springframework.boot.actuate.health.Status
import org.springframework.context.annotation.Configuration

@Configuration(proxyBeanMethods = false)
class MyHealthMetricsExportConfiguration(registry: MeterRegistry, healthEndpoint: HealthEndpoint) {

	init {
		// This example presumes common tags (such as the app) are applied elsewhere
		Gauge.builder("health", healthEndpoint) { health ->
			getStatusCode(health).toDouble()
		}.strongReference(true).register(registry)
	}

	private fun getStatusCode(health: HealthEndpoint) = when (health.health().status) {
		Status.UP -> 3
		Status.OUT_OF_SERVICE -> 2
		Status.DOWN -> 1
		else -> 0
	}

}