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