springboot可以通過實現@ManagedResource,@ManagedAttribute, or @ManagedOperation等接口,將bean暴露為MBean,開啟JMX功能需要添加配置:
spring.jmx.enabled=true
對應的MBean代碼如下:
import org.springframework.jmx.export.annotation.ManagedAttribute; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.stereotype.Component; @Component @ManagedResource(objectName = "com.mbean.demo:name=MBeanDemo") public class MBeanDemo { @ManagedAttribute public String getName() { return "MBean"; } @ManagedOperation public void shutdown() { System.exit(0); } }
暴露為MBean后,可以通過jconsole或者jvisualvm等工具,訪問Mbean的屬性或者調用方法:
如下圖,可以通過jvisualvm查看mbean的屬性或者調用shutdown方法等


springboot可以通過集成jolokia來使用HTTP形式訪問mbean
在pom.xml中添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
添加配置:
management.endpoint.jolokia.enabled=true management.endpoints.web.exposure.include=*
通過訪問http://localhost:8080/actuator/jolokia可以看到如下類似數據,即說明集成成功
{ "request": { "type": "version" }, "value": { "agent": "1.6.2", "protocol": "7.2", "config": { "listenForHttpService": "true", "authIgnoreCerts": "false", "agentId": "10.0.75.1-9200-5c9f0ca8-servlet", "debug": "false", "agentType": "servlet", "policyLocation": "classpath:\/jolokia-access.xml", "agentContext": "\/jolokia", "serializeException": "false", "mimeType": "text\/plain", "dispatcherClasses": "org.jolokia.http.Jsr160ProxyNotEnabledByDefaultAnymoreDispatcher", "authMode": "basic", "authMatch": "any", "streaming": "true", "canonicalNaming": "true", "historyMaxEntries": "10", "allowErrorDetails": "true", "allowDnsReverseLookup": "true", "realm": "jolokia", "includeStackTrace": "true", "useRestrictorService": "false", "debugMaxEntries": "100" }, "info": {} }, "timestamp": 1587714368, "status": 200 }
訪問http://localhost:8080/actuator/jolokia/read/com.mbean.demo:name=MBeanDemo可以看到對應MBean的屬性
{"request":{"mbean":"com.mbean.demo:name=MBeanDemo","type":"read"},"value":{"Name":"MBean"},"timestamp":1587714460,"status":200}
更多關於jolokia的使用可以參考官網:
Jolokia Protocol

