透過 JMX 進行監控和管理

Java Management Extensions (JMX) 提供了一種標準的機制來監控和管理應用。預設情況下,此功能未啟用。你可以透過設定配置屬性 spring.jmx.enabledtrue 來開啟它。Spring Boot 會暴露最合適的 MBeanServer 作為 Bean,其 ID 為 mbeanServer。任何使用 Spring JMX 註解(@org.springframework.jmx.export.annotation.ManagedResource@ManagedAttribute@ManagedOperation)標註的 Bean 都會暴露給它。

如果你的平臺提供了標準的 MBeanServer,Spring Boot 會使用它;如有必要,則預設使用 VM MBeanServer。如果這些都失敗了,就會建立一個新的 MBeanServer

spring.jmx.enabled 隻影響 Spring 提供的管理 Bean。啟用其他庫(例如 Log4j2Quartz)提供的管理 Bean 是獨立的。

有關更多詳細資訊,請參閱 JmxAutoConfiguration 類。

預設情況下,Spring Boot 還在 org.springframework.boot 域下將管理端點暴露為 JMX MBeans。要完全控制 JMX 域中的端點註冊,可以考慮註冊自己的 EndpointObjectNameFactory 實現。

自定義 MBean 名稱

MBean 的名稱通常由端點的 id 生成。例如,health 端點暴露為 org.springframework.boot:type=Endpoint,name=Health

如果你的應用包含多個 Spring ApplicationContext,可能會發現名稱衝突。要解決此問題,你可以將 spring.jmx.unique-names 屬性設定為 true,以便 MBean 名稱始終唯一。

你還可以自定義暴露端點的 JMX 域。以下設定顯示瞭如何在 application.properties 中執行此操作的示例:

  • Properties

  • YAML

spring.jmx.unique-names=true
management.endpoints.jmx.domain=com.example.myapp
spring:
  jmx:
    unique-names: true
management:
  endpoints:
    jmx:
      domain: "com.example.myapp"

停用 JMX 端點

如果你不想透過 JMX 暴露端點,可以將 management.endpoints.jmx.exposure.exclude 屬性設定為 *,如下例所示:

  • Properties

  • YAML

management.endpoints.jmx.exposure.exclude=*
management:
  endpoints:
    jmx:
      exposure:
        exclude: "*"