Skip to content

17.3 Gửi thông báo

Các MBean có thể đẩy (push) thông báo đến các client JMX quan tâm bằng cách sử dụng NotificationPublisher của Spring. NotificationPublisher có một phương thức duy nhất là sendNotification(), khi được cung cấp một đối tượng Notification, sẽ gửi thông báo đến bất kỳ client JMX nào đã đăng ký với MBean.

Để một MBean có thể gửi thông báo, nó phải triển khai interface NotificationPublisherAware, yêu cầu phải cài đặt phương thức setNotificationPublisher().
Ví dụ, giả sử bạn muốn gửi một thông báo sau mỗi 100 chiếc taco được tạo ra. Bạn có thể thay đổi lớp TacoCounter sao cho nó triển khai NotificationPublisherAware và sử dụng NotificationPublisher được tiêm vào để gửi thông báo mỗi khi đạt đến mốc 100 chiếc taco.

Đoạn mô tả sau cho thấy những thay đổi cần thực hiện trong TacoCounter để kích hoạt việc gửi thông báo như vậy.

Liệt kê 17.2 Gửi thông báo cho mỗi 100 chiếc taco

java
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;
  }
}

Trong client JMX, bạn cần đăng ký với MBean TacoCounter để nhận các thông báo. Sau đó, khi các chiếc taco được tạo ra, client sẽ nhận được thông báo mỗi khi đạt đến 100 chiếc. Hình 17.5 cho thấy cách các thông báo có thể xuất hiện trong JConsole.

Hình 17.5Hình 17.5 JConsole, sau khi đăng ký với MBean TacoCounter, nhận được thông báo sau mỗi 100 chiếc taco được tạo

Thông báo là một cách tuyệt vời để một ứng dụng chủ động gửi dữ liệu và cảnh báo đến một client giám sát mà không yêu cầu client phải liên tục truy vấn thuộc tính hoặc gọi thao tác được quản lý.

Released under the MIT License.