18.3 发送通知

MBean 可以使用 Spring 的 NotificationPublisher,将通知推送到感兴趣的 JMX 客户端。NotificationPublisher 有一个 sendNotification() 方法,当给定 Notification 对象时,会将通知发布到任何已经订阅此 MBean 的 JMX 客户端。

为了使 MBean 能够发布通知,它必须实现 NotificationPublisherAware 接口,该接口要求实现 setNotificationPublisher() 方法。例如,假设每生产 100 个玉米卷,您要发布一次通知,可以修改 TacoCounter 类,实现 NotificationPublisherAware 并使用注入的 NotificationPublisher 发送通知。下面的清单显示了,实现此功能后的 TacoCounter。

{% code title=”程序清单 18.2 每生产 100 个玉米卷就发送通知” %}

  1. @Service
  2. @ManagedResource
  3. public class TacoCounter
  4. extends AbstractRepositoryEventListener<Taco>
  5. implements NotificationPublisherAware {
  6. private AtomicLong counter;
  7. private NotificationPublisher np;
  8. ...
  9. @Override
  10. public void setNotificationPublisher(NotificationPublisher np) {
  11. this.np = np;
  12. }
  13. ...
  14. @ManagedOperation
  15. public long increment(long delta) {
  16. long before = counter.get();
  17. long after = counter.addAndGet(delta);
  18. if ((after / 100) > (before / 100)) {
  19. Notification notification = new Notification(
  20. "taco.count", this,
  21. before, after + "th taco created!");
  22. np.sendNotification(notification);
  23. }
  24. return after;
  25. }
  26. }

{% endcode %}

在 JMX 客户端中,您需要订阅 TacoCounter MBean 以接收通知。然后,随着玉米卷的生产,每生产 100 个玉米卷,客户端将收到一条通知。图 18.5 显示了在 JConsole 中显示的通知。

图 18.5 订阅 TacoCounter MBean 的 JConsole,每 100 个玉米卷被制造出来就收到一次通知。

推送通知是应用程序主动向客户端发送数据和警报的好方法,而不要求客户端轮询或主动发起调用操作。