发送通知

借助Spring的NotificationPublisher,MBean可以推送通知到对其感兴趣的JMX客户端。NotificationPublisher具有sendNotification()方法,可以在得到一个Notification对象时发送通知给任意订阅该MBean的JMX客户端。

要让某个MBean发送通知,必须为其实现NotificationPublisherAware接口,该接口要求实现一个setNotificationPublisher()方法。例如,我们希望每创建100个taco就发送一个通知。我们可以修改TacoCounter类,让它实现NotificationPublisherAware,并使用注入的NotificationPublisher在每创建100个taco时发送通知。程序清单17.2展现了启用通知功能TacoCounter所需的变更。

程序清单17.2 每创建100个taco就发送通知
package tacos.jmx;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.data.rest.core.event.AbstractRepositoryEventListener;
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.Service;

import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
import javax.management.Notification;

import tacos.Taco;
import tacos.data.TacoRepository;

@Service
@ManagedResource
public class TacoCounter
       extends AbstractRepositoryEventListener<Taco>
       implements NotificationPublisherAware {

  private AtomicLong counter;
  private NotificationPublisher np;

  @Override
  public void setNotificationPublisher(NotificationPublisher np) {
    this.np = np;
  }

...

  @ManagedOperation
  public long increment(long delta) {
    long before = counter.get();
    long after = counter.addAndGet(delta);
    if ((after / 100) > (before / 100)) {
      Notification notification = new Notification(
          "taco.count", this,
          before, after + "th taco created!");
      np.sendNotification(notification);
    }
    return after;
  }

}

在JMX客户端中,我们需要订阅TacoCounter MBean来接收通知。每创建100个taco,客户端就会收到通知。图17.5展现了通知在JConsole中的样子。

通知是应用程序主动向监视客户端发送数据和告警的好办法。这样做可以避免客户端轮询托管属性或调用托管操作。

image 2024 03 14 15 46 26 778
Figure 1. 图17.5 JConsole订阅了TacoCounter MBean,每创建100个taco就会收到通知

小结

  • 大多数Actuator端点都可以作为MBean使用,可以被JMX客户端消费。

  • Spring会自动启用JMX,用来监控Spring应用上下文中的bean。

  • Spring bean可以通过添加@ManagedResource注解导出为MBean。通过为bean类添加@ManagedOperation和@ManagedAttribute注解,它的方法和属性可以导出为托管的操作和属性。

  • Spring bean可以使用NotificationPublisher发送通知给JMX客户端。