ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Spring Boot Admin 参考指南:事件类型、REST API 与配置属性全解析

Spring Boot Admin 参考指南:事件类型、REST API 与配置属性全解析 Spring Boot Admin 参考指南事件类型、REST API 与配置属性全解析【免费下载链接】spring-boot-adminAdmin UI for administration of spring boot applications项目地址: https://gitcode.com/gh_mirrors/sp/spring-boot-admin本指南系统整理 Spring Boot Admin 官方参考文档10-reference/index.md中的核心内容涵盖实例生命周期事件InstanceEvent、服务端 HTTP API供内置 SPA 使用、通用配置属性、状态值优先级与配置元数据。读完本文你将掌握事件监听与过滤、REST 接口调用、上下文路径与客户端注册等关键配置方式并能结合仓库源码理解其底层实现原理。参考文档总览Spring Boot Admin 的 Reference 部分分为两大主题均位于 spring-boot-admin-docs/src/site/docs/10-reference/ 目录下文档内容适用场景Event Types Reference全部InstanceEvent类型、生命周期与监听方式自定义通知、告警、事件驱动的监控扩展REST API Reference服务端 HTTP API实例注册、事件流、操作等集成调试、SPA 数据源、外部工具对接重要提示REST API 主要为内置单页应用SPA设计不属于稳定的公开 API不承诺版本化兼容外部集成时应谨慎使用详见下文API 版本与稳定性章节。事件类型参考InstanceEvent事件是 Spring Boot Admin Server 与外部系统交互最稳定的途径。所有事件都继承自抽象基类InstanceEvent其源码位于 InstanceEvent.javapublic abstract class InstanceEvent implements Serializable { private final InstanceId instance; // 唯一实例标识 private final long version; // 事件版本每个实例单调递增 private final Instant timestamp; // 事件发生时间ISO-8601 private final String type; // 事件类型常量 }通用属性说明instance实例唯一 ID如abc123def456version针对同一实例单调递增的版本号用于保证事件有序timestamp事件创建时间type标识事件类型的字符串常量事件生命周期一个实例的典型事件序列如下1. REGISTERED → 实例首次注册 2. ENDPOINTS_DETECTED → 发现 Actuator 端点 3. STATUS_CHANGED → 健康状态更新为 UP 4. INFO_CHANGED → 加载 Info 端点数据 5. STATUS_CHANGED → 生命周期内状态持续变化 6. REGISTRATION_UPDATED → 注册信息变更可选 7. DEREGISTERED → 实例注销六种事件类型速查事件类型描述REGISTERED实例首次注册REGISTRATION_UPDATED实例注册信息发生变化DEREGISTERED实例注销STATUS_CHANGED健康状态发生变化ENDPOINTS_DETECTED发现 Actuator 端点INFO_CHANGEDInfo 端点数据发生变化每种事件在仓库中都有对应的独立实现类位于 domain/events 目录并定义类型常量例如 InstanceStatusChangedEvent.java 中的public static final String TYPE STATUS_CHANGED。1. REGISTERED类InstanceRegisteredEvent见 InstanceRegisteredEvent.java触发时机实例首次向 Admin Server 注册时。Payload携带完整的Registration信息其字段校验逻辑定义在 Registration.javaname应用名称managementUrlActuator 基础 URL可能与应用端口/上下文不同必须是绝对 URLhealthUrl健康端点绝对 URL必填Admin Server 依赖它判定实例状态serviceUrl业务应用公共基础 URL用于打开应用链接可通过元数据service-url/service-path覆盖source注册来源如http-api、discoverymetadata自定义元数据 Map示例事件 JSON{ instance: abc123def456, version: 0, timestamp: 2026-02-07T10:00:00Z, type: REGISTERED, registration: { name: my-service, managementUrl: http://localhost:8080/actuator, healthUrl: http://localhost:8080/actuator/health, serviceUrl: http://localhost:8080, source: http-api, metadata: { startup: 2026-02-07T09:59:55Z } } }典型用途发送欢迎通知、初始化实例级监控、记录新实例注册日志、触发端点发现。监听示例Component public class RegistrationListener { EventListener public void onInstanceRegistered(InstanceRegisteredEvent event) { log.info(New instance registered: {} at {}, event.getRegistration().getName(), event.getRegistration().getServiceUrl()); } }2. REGISTRATION_UPDATED类InstanceRegistrationUpdatedEvent触发时机实例更新注册信息URL、元数据等时。常见触发原因实例 IP 变更、管理端口变更、元数据更新、健康 URL 变更。Payload更新后的Registration字段同上。示例中可见实例迁移到192.168.1.100后三个 URL 同步更新且元数据记录了新版本号version: 2.0.0。典型用途检测实例迁移、更新监控端点、追踪配置变更、触发端点重新发现。3. DEREGISTERED类InstanceDeregisteredEvent触发时机实例注销正常关闭或显式注销时。Payload无附加字段仅包含基类的instance、version、timestamp、type{ instance: abc123def456, version: 10, timestamp: 2026-02-07T12:00:00Z, type: DEREGISTERED }典型用途发送下线通知、清理实例专属资源、记录实例生命周期、对异常退出触发告警。监听示例EventListener public void onInstanceDeregistered(InstanceDeregisteredEvent event) { Instant timestamp event.getTimestamp(); long version event.getVersion(); log.info(Instance {} deregistered after {} events, event.getInstance(), version); // Cleanup resources cleanupResourcesFor(event.getInstance()); }4. STATUS_CHANGED类InstanceStatusChangedEvent见 InstanceStatusChangedEvent.java触发时机实例健康状态变化时。PayloadStatusInfo对象其状态常量和排序逻辑定义在 StatusInfo.javastatus当前状态UP/DOWN/OUT_OF_SERVICE/UNKNOWN/OFFLINE/RESTRICTEDdetails来自 Actuator health 端点的健康详情 Map从源码可以看到StatusInfo.from()同时兼容 Actuator V2details键与 V3components键两种响应格式。示例事件{ instance: abc123def456, version: 3, timestamp: 2026-02-07T10:05:00Z, type: STATUS_CHANGED, statusInfo: { status: UP, details: { diskSpace: { status: UP, total: 500000000000, free: 250000000000 }, db: { status: UP, database: PostgreSQL, validationQuery: isValid() } } } }典型用途状态变化告警UP → DOWN、统计运行/停机时间、触发自动化恢复、更新仪表盘。监听示例EventListener public void onStatusChanged(InstanceStatusChangedEvent event) { StatusInfo statusInfo event.getStatusInfo(); String status statusInfo.getStatus(); if (DOWN.equals(status)) { alertService.sendAlert( Instance event.getInstance() is DOWN, statusInfo.getDetails() ); } }5. ENDPOINTS_DETECTED类InstanceEndpointsDetectedEvent触发时机发现 Actuator 端点时。PayloadEndpoints对象包含Endpoint列表每项含id端点 ID如health、metrics、env、loggersurl端点完整 URL典型用途根据可用端点启用/禁用 UI 视图、开始监控指定端点、校验预期端点是否就绪、触发自定义端点轮询。监听示例EventListener public void onEndpointsDetected(InstanceEndpointsDetectedEvent event) { Endpoints endpoints event.getEndpoints(); boolean hasMetrics endpoints.get(metrics).isPresent(); boolean hasLoggers endpoints.get(loggers).isPresent(); if (hasMetrics hasLoggers) { // Enable advanced monitoring advancedMonitoring.enable(event.getInstance()); } }6. INFO_CHANGED类InstanceInfoChangedEvent触发时机/actuator/info数据变化时。PayloadInfo对象包含任意键值对常见内容build构建信息版本、时间、artifactgitGit 信息commit、branch、time自定义应用元数据典型用途追踪部署版本、在 UI 展示构建信息、校验线上版本、触发版本相关逻辑。事件排序事件按version号排序该版本号对每个实例单调递增version 0: REGISTERED version 1: ENDPOINTS_DETECTED version 2: STATUS_CHANGED (to UP) version 3: INFO_CHANGED version 4: STATUS_CHANGED (to DOWN) version 5: STATUS_CHANGED (to UP) version 6: DEREGISTERED关键点版本号在单个实例内唯一且只会增长消费端可据此安全重放或对齐事件顺序。事件持久化事件存储在InstanceEventStore中仓库提供两种实现InMemoryEventStore非持久化重启后丢失默认HazelcastEventStore分布式存储集群内持久化为防止事件无限增长支持事件压缩每个实例仅保留最近 N 条spring: boot: admin: event-store: max-log-size-per-aggregate: 100 # 每个实例保留最近 100 条事件监听事件Spring 事件监听器Component public class MyEventListener { EventListener public void onAnyInstanceEvent(InstanceEvent event) { log.info(Event: {} for instance {} at version {}, event.getType(), event.getInstance(), event.getVersion()); } EventListener public void onSpecificEvent(InstanceStatusChangedEvent event) { // Handle specific event type } }自定义 NotifierComponent public class CustomNotifier extends AbstractEventNotifier { public CustomNotifier(InstanceRepository repository) { super(repository); } Override protected MonoVoid doNotify(InstanceEvent event, Instance instance) { return Mono.fromRunnable(() - { switch (event.getType()) { case STATUS_CHANGED: handleStatusChange((InstanceStatusChangedEvent) event); break; case REGISTERED: handleRegistration((InstanceRegisteredEvent) event); break; // Handle other events } }); } }事件流SSE通过 REST API 订阅实时事件流curl -N http://localhost:8080/instances/events返回 Server-Sent EventsSSE流data:{instance:abc123,version:0,type:REGISTERED,...} data:{instance:abc123,version:1,type:ENDPOINTS_DETECTED,...} data:{instance:abc123,version:2,type:STATUS_CHANGED,...}事件过滤使用FilteringNotifier按类型过滤事件过滤表达式基于 SpELSpring Expression LanguageBean public FilteringNotifier filteringNotifier(Notifier delegate, InstanceRepository repository) { FilteringNotifier notifier new FilteringNotifier(delegate, repository); notifier.setFilterExpression(!(type INFO_CHANGED)); // 排除 INFO_CHANGED return notifier; }可用变量type事件类型字符串、instance实例 ID、version事件版本以及事件专属字段如STATUS_CHANGED的statusInfo.status。过滤表达式示例// 仅关注 DOWN 事件 type STATUS_CHANGED statusInfo.status DOWN // 排除 INFO_CHANGED 和 ENDPOINTS_DETECTED !(type INFO_CHANGED || type ENDPOINTS_DETECTED) // 仅生产环境实例通过元数据过滤 metadata[environment] production事件提醒使用RemindingNotifier对持续处于非 UP 状态的实例周期性地发送提醒Bean public RemindingNotifier remindingNotifier(Notifier delegate, InstanceRepository repository) { RemindingNotifier notifier new RemindingNotifier(delegate, repository); notifier.setReminderPeriod(Duration.ofMinutes(10)); notifier.setCheckReminderInterval(Duration.ofSeconds(60)); return notifier; }即实例状态在reminderPeriod过后仍非 UP则每轮检查间隔重新发送一次通知。REST API 参考Base URL 与内容类型默认基础 URL 为http://localhost:8080。配置自定义上下文路径后见下文Server Context Path基础 URL 变为http://localhost:8080/admin。内容类型约定请求application/json响应application/json或application/haljson流式响应text/event-streamSSE认证若启用 Spring Security所有端点都需要认证curl -u user:password http://localhost:8080/instances或使用你安全配置中约定的 token 认证方式。Instances API注册实例POST /instances请求体{ name: my-service, managementUrl: http://localhost:8081/actuator, healthUrl: http://localhost:8081/actuator/health, serviceUrl: http://localhost:8081, metadata: { startup: 2026-02-07T10:00:00Z, tags: { environment: production } } }返回201 Created响应体为实例 ID响应头Location: /instances/abc123def456{ id: abc123def456 }源码印证该端点实现在 InstancesController.java 的register()方法中——它会通过Registration.copyOf(registration).source(http-api).build()强制将source标记为http-api再调用registry.register()并返回201 Created与Location头。curl -X POST http://localhost:8080/instances \ -H Content-Type: application/json \ -d { name: my-service, managementUrl: http://localhost:8081/actuator, healthUrl: http://localhost:8081/actuator/health, serviceUrl: http://localhost:8081 }列出全部实例GET /instances返回200 OK及实例数组含id、version、registration、statusInfo、statusTimestamp、info、endpoints、buildVersion、tags等字段。对应源码中的instances()方法会过滤掉未注册实例filter(Instance::isRegistered)。curl http://localhost:8080/instances按名称列出实例GET /instances?name{name}name为必填参数返回与列表接口相同结构但已按名称过滤。对应源码instances(RequestParam(name) String name)内部通过registry.getInstances(name)查询。curl http://localhost:8080/instances?namemy-service获取单个实例GET /instances/{id}路径参数id为实例 IDcurl http://localhost:8080/instances/abc123def456注销实例DELETE /instances/{id}成功返回204 No Contentcurl -X DELETE http://localhost:8080/instances/abc123def456实例事件流GET /instances/events流式返回所有实例的实时事件text/event-streamcurl -N http://localhost:8080/instances/events心跳机制服务端每 10 秒发送一次 ping 注释保持连接。源码 InstancesController.java 中的PING_FLUX即Flux.interval(Duration.ZERO, Duration.ofSeconds(10L))印证了该行为。JavaScript 客户端示例const eventSource new EventSource(http://localhost:8080/instances/events); eventSource.onmessage (event) { const instanceEvent JSON.parse(event.data); console.log(Event:, instanceEvent.type, for, instanceEvent.instance); };单实例事件流GET /instances/{id}/events只订阅指定实例的事件curl -N http://localhost:8080/instances/abc123def456/eventsApplications APIApplications 表示名称相同的实例组成的逻辑分组。端点方法说明示例/applicationsGET列出全部应用按名称分组含status与instancescurl http://localhost:8080/applications/applications/{name}GET获取单个应用不存在时返回404 Not Foundcurl http://localhost:8080/applications/my-service/applications/eventsGET订阅应用级事件流SSEcurl -N http://localhost:8080/applications/events/applicationsPOST手动触发从服务发现刷新全部实例如 Eureka、Consul 场景curl -X POST http://localhost:8080/applications/applications/{name}DELETE注销某应用的全部实例返回204 No Contentcurl -X DELETE http://localhost:8080/applications/my-service实例 Actuator 代理Admin Server 会把对实例 Actuator 端点的请求代理转发到目标实例通用模式GET /instances/{id}/actuator/{endpoint}# 健康状态 curl http://localhost:8080/instances/abc123/actuator/health # 指标列表 curl http://localhost:8080/instances/abc123/actuator/metrics # 指定指标 curl http://localhost:8080/instances/abc123/actuator/metrics/jvm.memory.used # 环境属性 curl http://localhost:8080/instances/abc123/actuator/env # 日志配置 curl http://localhost:8080/instances/abc123/actuator/loggers常用端点速查端点说明/actuator/health健康状态/actuator/info构建与应用信息/actuator/metrics指标列表/actuator/metrics/{name}指定指标/actuator/env环境属性/actuator/loggers日志器配置/actuator/loggers/{name}指定日志器/actuator/httptraceHTTP 追踪/actuator/threaddump线程转储/actuator/heapdump堆转储二进制/actuator/jolokia通过 Jolokia 访问 JMX修改日志级别POST /instances/{id}/actuator/loggers/{name}curl -X POST http://localhost:8080/instances/abc123/actuator/loggers/com.example \ -H Content-Type: application/json \ -d {configuredLevel:DEBUG}实例操作操作端点返回示例重启POST /instances/{id}/actuator/restart200 OKcurl -X POST http://localhost:8080/instances/abc123/actuator/restart优雅关闭POST /instances/{id}/actuator/shutdown200 OKbody 如{message: Shutting down, bye...}curl -X POST http://localhost:8080/instances/abc123/actuator/shutdown⚠️危险操作警告重启/关闭需依赖目标实例启用spring-boot-starter-actuator的对应端点且务必做好端点安全加固生产环境请谨慎评估后再执行。错误响应状态码含义示例响应体400 Bad Request请求体或参数非法{error: Bad Request, message: Invalid registration data, status: 400}404 Not Found实例或应用不存在{error: Not Found, message: Instance not found: abc123, status: 404}500 Internal Server Error服务端错误{error: Internal Server Error, message: Failed to register instance, status: 500}CORS 配置spring: boot: admin: cors: allowed-origins: http://localhost:3000 allowed-methods: GET,POST,DELETE allowed-headers: * exposed-headers: Location allow-credentials: true max-age: 3600其他行为说明限流无内置限流如需要请在反向代理nginx、API 网关层实现。分页实例与应用列表接口不支持分页大规模部署建议按名称过滤或使用服务发现过滤。缓存默认不缓存响应需要时可在反向代理层添加缓存头。WebSocket不支持实时更新请统一使用 SSE。API 客户端示例JavaRestTemplateRestTemplate restTemplate new RestTemplate(); // Register instance Registration registration Registration.create(my-service) .managementUrl(http://localhost:8081/actuator) .healthUrl(http://localhost:8081/actuator/health) .serviceUrl(http://localhost:8081) .build(); ResponseEntityMap response restTemplate.postForEntity( http://localhost:8080/instances, registration, Map.class ); String instanceId (String) response.getBody().get(id);JavaScript/TypeScriptfetchconst registration { name: my-service, managementUrl: http://localhost:8081/actuator, healthUrl: http://localhost:8081/actuator/health, serviceUrl: http://localhost:8081 }; const response await fetch(http://localhost:8080/instances, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify(registration) }); const { id } await response.json(); console.log(Instance ID:, id);Pythonrequestsimport requests registration { name: my-service, managementUrl: http://localhost:8081/actuator, healthUrl: http://localhost:8081/actuator/health, serviceUrl: http://localhost:8081 } response requests.post( http://localhost:8080/instances, jsonregistration ) instance_id response.json()[id] print(fInstance ID: {instance_id})配置属性参考Server Context Path为 Admin Server 设置独立上下文路径避免与应用其他路径冲突spring: boot: admin: context-path: /admin # 默认: /设置后REST API 基础路径变为{context-path}/instances例如http://localhost:8080/admin/instances。Client Registration客户端注册到 Admin Server 的基础配置spring: boot: admin: client: url: http://localhost:8080 instance: name: ${spring.application.name}spring.boot.admin.client.url指向 Admin Server 地址instance.name指定注册时使用的应用名此处引用spring.application.name。更完整的客户端注册说明见 Client Registration。属性前缀总览所有 Spring Boot Admin 属性均使用以下前缀服务端属性spring.boot.admin.*— 核心服务端配置spring.boot.admin.ui.*— UI 定制spring.boot.admin.discovery.*— 服务发现spring.boot.admin.monitor.*— 监控设置spring.boot.admin.notify.*— 通知设置客户端属性spring.boot.admin.client.*— 客户端配置spring.boot.admin.client.instance.*— 实例元数据完整属性清单可参考 Server Configuration 与 Client Properties。配置元数据Spring Boot Admin 提供完整的配置元数据支持 IDE 自动补全。引入服务端依赖dependency groupIdde.codecentric/groupId artifactIdspring-boot-admin-server/artifactId /dependency元数据文件包括spring-configuration-metadata.json服务端additional-spring-configuration-metadata.json客户端在 IDE 中编写application.yml时即可获得属性提示、默认值与类型校验。状态值优先级健康状态按以下顺序确定严重程度来自 StatusInfo.java 中的STATUS_ORDER常量severity()方法即按该顺序比较DOWN— 应用不健康OUT_OF_SERVICE— 暂时不可用OFFLINE— 实例无响应UNKNOWN— 无法确定状态UP— 应用健康RESTRICTED— 自定义状态应用自定义其中RESTRICTED是唯一由应用自行定义的状态可通过StatusInfo.ofRestricted()构造其余为 Spring Boot Actuator 或 Admin Server 产生。聚合多个实例的应用状态时Admin Server 会取最严重者。API 版本与稳定性Spring Boot Admin 不为其 REST API 提供版本化。核心事实如下Base Path{server.context-path}/instances默认/instancesContent Typeapplication/json集合端点使用 HAL JSON稳定性REST API 仅供内置 SPA 使用可能随时变更且不另行通知需要稳定集成的场景官方建议改用事件通知系统即上文的事件监听与 Notifier 机制这也是对外集成更推荐的方式。延伸阅读Server ConfigurationClient RegistrationCustomizationNotificationsCustom NotifiersInstance Registry【免费下载链接】spring-boot-adminAdmin UI for administration of spring boot applications项目地址: https://gitcode.com/gh_mirrors/sp/spring-boot-admin创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表