Actuator可以使用http base方式或者JMX方式公布开端点,从而提供spring应用的运行信息,以下会介绍JMX的使用- Spring Boot 引用中默认是启用
JMX(Java Management Extensions)的,并且默认是公开的MBeans,可以直接使用jdk自带的jconsole(shell窗口使用命令jconsole即可)客户端查看Mbeans- 使用
JMX,那么所有的Actuator端点(除了/heapdump)会通过MBeans进行公开的
1. 使用Actuator MBeans
默认情况下是启用
JMX的,因此只需要通过JMX客户端使用其公开的端点即可,可以自由选择JMX客户端查看其端点,此处使用JDK自带的JConsole打开
shell窗口出入命令jconsole即可打开界面然后连接运行的应用,查看MBean信息,可以发现org.springframework.boot下面已经公开了MBeans信息展开目录树可以看到具体端点下面有具体操作,然后点击按钮即可获取到端点信息
与
HTTP bease方式不同,JMX默认情况下是公开MBeans的,可以通过配置设置需要公开的端点设置公开的端点
management: endpoints: jmx: exposure: include: health,info,bean,conditions设置排除某些端点
management: endpoints: jmx: exposure: exclude: env,metrics
2. 创建自定义的MBeans
Spring 可以很容易的将任何
Bean作为JMX MBean进行公开,只需要在Bean类使用@ManagedResource注解,在方法上使用@ManagedOperation或者@ManagedAttribute注解即可实例
@Service //以便component scanning获取 @ManagedResource //暴露端点 public class TacoMBean { private AtomicInteger count; public TacoMBean() { this.count = new AtomicInteger(0); } @ManagedAttribute //操作 public int getCount(){ return count.get(); } @ManagedOperation //操作 public int increment(int i){ return count.getAndAdd(i); } }
3. Sending notifications(推送通知)
通过使用
Spring的NotificationPublisher可以让MBeans将消息推送到JMX clentsNotificationPublisher有一个sendNotification()方法可以实现发布通知到任何一个订阅了Mbean的JMX clients上推送通知是一种服务端直接想客户端发送数据或者警告信息的很好方式,无需客户端通过轮询方式查询
MBean只要实现NotificationPublisherAware接口并实现其setNotificationPublisher()方法即可@Service //以便component scanning获取 @ManagedResource //暴露端点 public class TacoMBean implements NotificationPublisherAware { private AtomicInteger count; private NotificationPublisher np; public TacoMBean() { this.count = new AtomicInteger(0); } @ManagedAttribute //操作 public int getCount(){ return count.get(); } @ManagedOperation //操作 public int increment(int i){ if(i>10){ np.sendNotification(new Notification( "taco.count", this, count.get(), "输入参数大于10" )); } return count.getAndAdd(i); } @Override public void setNotificationPublisher(NotificationPublisher notificationPublisher) { this.np = notificationPublisher; } }