JMX Learning Notes (ii)-notification

Source: Internet
Author: User
Tags getmessage server port

Notification notice, can also be understood as a message, there is a notice, there must be a broadcast of the notification, JMX here using a way of subscribing, similar to the Observer mode, register an observer to the broadcast, when there is notification, broadcast by calling the Observer, the notice.

Here's a simple example of server configuration, first defining our Mbean interface:

Java codePackageCom.haitao.jmx.mbeans.server; /** * * Server Configure MBean * * @author haitao.tu * * * * PublicInterfaceServerconfigurembean { PublicvoidSetport (intPort); PublicintGetport (); PublicvoidSethost (String host); PublicString GetHost (); }

Package com.haitao.jmx.mbeans.server;

/**
 * * 
 Server Configure MBean
 * 
 * @author haitao.tu
 *
*/public interface Serverconfigurembean {public

	void setport (int port);
	
	public int getport ();
	
	public void Sethost (String host);
	
	Public String gethost ();
	
}

Next, we will want to implement this Mbean interface as in the first section, and inherit Notificationbroadcastersupport to provide the broadcast service:

Java codePackageCom.haitao.jmx.mbeans.server;ImportJava.util.concurrent.atomic.AtomicLong;ImportJavax.management.AttributeChangeNotification;ImportJavax.management.NotificationBroadcasterSupport; /** * Server Configure * * @author haitao.tu * * * * * PublicclassServerconfigureextendsNotificationbroadcastersupportImplementsServerconfigurembean {PrivateAtomiclong SequenceNumber =NewAtomiclong (1);PrivateintPortPrivateString host; @Override PublicvoidSetport (intPort) {intOldport = This. Port; This. Port = port; Attributechangenotification notification =NewAttributechangenotification ( This, Sequencenumber.getandincrement (), System.currenttimemillis (), A Ttributechangenotification.attribute_change, "Server Port Change", "Java.lang.Intege R ", Oldport +" ", This. Port + "");Super. sendnotification (notification); } @Override PublicvoidSethost (String host) {String oldHost = This. host; This. host = host; Attributechangenotification notification =NewAttributechangenotification ( This, Sequencenumber.getandincrement (), System.currenttimemillis (), A Ttributechangenotification.attribute_change, "Server Host Change", "java.lang.String ", OldHost, This. host);Super. sendnotification (notification); } @Override PublicintGetport () { returnPort } @Override PublicString GetHost () { return host;       &nbsp}      }  

Package com.haitao.jmx.mbeans.server;

Import Java.util.concurrent.atomic.AtomicLong;
Import javax.management.AttributeChangeNotification;

Import Javax.management.NotificationBroadcasterSupport; /** * Server Configure * * * @author haitao.tu * */public class Serverconfigure extends Notificationbroadcastersuppor

	T implements Serverconfigurembean {private Atomiclong sequencenumber = new Atomiclong (1);

	private int port;

	Private String host;
		@Override public void Setport (int port) {int oldport = This.port;
		This.port = port; Attributechangenotification notification = new Attributechangenotification (this, sequencenumber.getandincrement () , System.currenttimemillis (), Attributechangenotification.attribute_change, "Server Port Change", "java.la Ng.
		Integer ", Oldport +" ", This.port +" ");
	Super.sendnotification (notification);
		@Override public void Sethost (string host) {string oldHost = This.host;
		This.host = host; AttribUtechangenotification notification = new Attributechangenotification (this, sequencenumber.getandincrement (), System.currenttimemillis (), Attributechangenotification.attribute_change, "Server Host Change", "java.lang.Str
		ing ", oldHost, This.host);
	Super.sendnotification (notification);
	@Override public int Getport () {return port;
	@Override public String GetHost () {return host;
 }

}

In the Setport and Sethos methods, a new attributechangenotification is first introduced, This class is a subclass of Javax.management.Notification, and Javax.management.Notification

This class is also a subclass of Java.util.EventObject, which confirms the above that the JMX notification mechanism uses the observer design pattern.

Javax.management.Notification is a JMX notification core class that will need to be expanded or otherwise JMX-brought messages to be integrated from this class.

Attributechangenotification according to the class name, is a notification of property changes, the method parameters are as follows:

Object source,//event source, passed to Java.util.EventObject source

Long sequencenumber,//notification number, identifying the counter for each notification

Long TimeStamp,//time stamp issued by notification

String msg,//message sent by notification

String AttributeName,//Modified property name

String AttributeType,//modified property type

Object OldValue,//Modified property modifies previous value

Object newvalue//Modified value after modified property

According to the Observer pattern, the event and the broadcast are made up, so here inherits the Notificationbroadcastersupport to provide the broadcasting mechanism,

Call NOTIFICATIONBROADCASTERSUPPORTR's sendnotification (notification) to send a broadcast that broadcasts will be based on registered observers

To inform the Observer.

SendNotification in JDK1.6 is sent by executor to send notifications, and the default call thread is sent synchronously:

Java code public Notificationbroadcastersupport (Executor Executor, Mbeannotificationinfo. .           info) { this. Executor = (Executor!= null)? Executor:defaultexecutor; Notifinfo = info = null ?        NO_NOTIFICATION_INFO:info.clone (); }

Public Notificationbroadcastersupport (Executor Executor,
					  mbeannotificationinfo ... info) {
	This.executor = ( Executor!= null)? Executor:defaultexecutor;

	Notifinfo = info = null? NO_NOTIFICATION_INFO:info.clone ();
    }

Java code private final static Executor defaultexecutor = new Executor () {//            Directexecutor using caller thread public void Execute (Runnable r) {R.run (); }        };

Private final static Executor Defaultexecutor = new Executor () {
	    //directexecutor using caller thread public
	    void Execute (Runnable r) {
		r.run ();
	    }
	

If you want to send notifications asynchronously, you can pass the executor, such as Threadpoolexecutor, to the asynchronous execution in the constructor method.

Next, we have to write an observer to receive the notice we send:

Java codePackageCom.haitao.jmx.mbeans.server;ImportJavax.management.Notification;ImportJavax.management.NotificationListener; /** * Server Configure Notification Listener * * @author haitao.tu * * * * PublicclassServerconfigurenotificationlistenerImplementsNotificationlistener {@Override PublicvoidHandlenotification (Notification Notification, Object handback) {log ("SequenceNumber:" + Notification.getsequen            Cenumber ());            Log ("Type:" + notification.gettype ());            Log ("message:" + notification.getmessage ());            Log ("Source:" + notification.getsource ());        Log ("TimeStamp:" + notification.gettimestamp ()); }PrivatevoidLog (String message) {SYSTEM.OUT.PRINTLN (message); }       }

Package com.haitao.jmx.mbeans.server;

Import javax.management.Notification;
Import Javax.management.NotificationListener;

/**
 * Server Configure Notification Listener
 * * 
 @author haitao.tu
 */public
class Serverconfigurenotificationlistener implements
		Notificationlistener {

	@Override public
	Void Handlenotification (Notification Notification, Object handback) {
		log ("SequenceNumber:" + Notification.getsequencenumber ());
		Log ("Type:" + notification.gettype ());
		Log ("message:" + notification.getmessage ());
		Log ("Source:" + notification.getsource ());
		Log ("TimeStamp:" + notification.gettimestamp ());
	}

	private void log (String message) {
		System.out.println (message);
	}

}

Here is simply the output of the notification content, in this class we implement the Notificationlistener interface, we can see that the interface only one method,

is to process the message, to the following, look at the Notificationlistener interface code:

Java codePackageJavax.management;ImportJava.util.EventListener;    /** * Should is implemented by a object that wants to receive notifications. * * @since 1.5 * * PublicInterfaceNotificationlistenerextends java.util.EventListener   {            /**       * invoked when a jmx notification occurs.       * The implementation of this method should  Return as soon as possible, to avoid       *  Blocking its notification broadcaster.       *       *  @param  notification The  notification.           *  @param  handback An  Opaque object which helps the listener to associate information       * regarding the MBean emitter. This object is  Passed to the mbean during the     &nbsP; * addlistener call and resent, without modification, to the  listener. The MBean object        * should n

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.