![]() ![]() ![]() ![]() ![]() ![]() |
JMX provides two ways to monitor MBeans: MBeans can emit notifications when specific events occur (such as a change in an attribute value), or a special type of MBean called a monitor MBean can poll another MBean and periodically emit notifications to describe an attribute value. You create Java classes called listeners that listen for these notifications and respond appropriately. For example, your management utility can include a listener that receives notifications when applications are deployed, undeployed, or redeployed.
All WebLogic Server configuration MBeans emit notifications when attribute values change, and some runtime MBeans do.
The following sections describe working with notifications and listeners:
If the MBean that you want to monitor emits notifications, you can choose whether to create a listener object that listens for changes in the MBean or a monitor MBean that periodically polls the MBean and emits notifications only when its attributes change in specific ways. The technique that you choose depends mostly on the complexity of the situations in which you want to receive notifications.
If your requirements are simple, registering a listener directly with an MBean is the preferred technique because the MBean pushes its notifications to your listener and you are notified of a change almost immediately. However, the base classes that you implement for a listener and optional filter (javax.management.NotificationListener
and NotificationFilter
) provide few facilities for comparing values with thresholds and other values. (See the
javax.management
package in the J2SE 5.0 API Specification.)
If your notification requirements are sufficiently complex, or if you want to monitor a group of changes that are not directly associated with a single change in the value of an MBean attribute, use a monitor MBean. (See the
javax.management.monitor
package in the J2SE 5.0 API Specification.) The monitor MBeans provide a rich set of tools for comparing data and sending notifications only under specific circumstances. However, the monitor periodically polls the observed MBean for changes in attribute value and you are notified of a change only as frequently as the polling interval that you specify.
The WebLogic Server JMX agent and WebLogic Server MBeans emit different types of notification objects for different types of events. Many event types trigger multiple MBeans to emit notifications at different points within the event process. Table 7-1 describes common event types and recommends the MBean with which a JMX monitoring application should register to listen for notifications.
Note: | Each JMX notification object contains an attribute named Type , which contains a dot-delimited string. Do not confuse discussions of this Type attribute with a notification’s object type. |
Note: | The Type attribute offers a way to categorize and filter notifications. For example, if your custom MBeans emit notifications, JMX conventions suggest that you set your notification object’s Type attribute to a string that starts with your company name: mycompany.myapp.valueIncreased . |
Note: | All JMX notification objects extend the javax.management.Notification object type. JMX and WebLogic Server define additional notification object types, such as javax.management.AttributeChangeNotification . The additional object types contain specialized sets of information that are appropriate for different types of events. (See the list of Notification subclasses for
javax.management.Notification in the J2SE 5.0 API Specification. Also see
weblogic.management.logging.WebLogicLogNotification in the WebLogic Server API Reference.) |
To receive a notification when a server starts or stops, register a listener with each server’s
ServerLifeCycleRuntimeMBean in the Domain Runtime MBean Server and configure an AttributeChangeNotificationFilter .
Each server in a domain provides its own
ServerLifeCycleRuntimeMBean , which is available through the Domain Runtime MBean Server even if the server itself is not active. When you start a server instance, the server’s ServerLifeCycleRuntimeMBean updates the value of its State attribute and emits an AttributeChangeNotification .
For an example of such a listener and filter, see Listening for Notifications from WebLogic Server MBeans: Main Steps.
|
|||
When you create a resource such as a server or a JDBC data source, WebLogic Server registers the resource’s configuration MBean in the MBean server. When you delete a resource, WebLogic Server unregisters the configuration MBean.
To listen for the registration and unregistration of MBeans, register a listener with
javax.management.MBeanServerDelegate , which emits notifications of type javax.management.MBeanServerNotification when MBeans are registered or unregistered.
If you register a listener with
MBeanServerDelegate in the Edit MBean Server, you receive notifications when someone modifies the pending MBean hierarchy.
If you register a listener in the Runtime MBean Server or the Domain Runtime MBean Server, you receive notifications only when pending changes have been successfully activated in the domain. If you are interested solely in monitoring configuration data (and are not interested in monitoring runtime statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.
|
|||
All configuration MBeans emit notifications of type
AttributeChangeNotification when their attribute values change.
To receive this notification, register a listener with the MBean that is in the Domain Runtime MBean Server or Runtime MBean Server (see Best Practices: Choosing an MBean Server).
If you register an MBean in the Edit MBean Server, you receive notifications when someone modifies the pending MBean hierarchy.
If you register a listener in the Runtime MBean Server or the Domain Runtime MBean Server, you receive notifications only when pending changes have been successfully activated in the domain. If you are interested solely in monitoring configuration data (and are not interested in monitoring runtime statistics), register your listener in only one Runtime MBean Server. See Best Practices: Choosing an MBean Server.
|
|||
Some runtime MBeans emit notifications of type
AttributeChangeNotification when their attribute values change. To receive this notification, register a listener with the MBean in the Domain Runtime MBean Server.
If a runtime MBean does not emit notifications, you can create a monitor MBean that polls the runtime MBean. See Using Monitor MBeans to Observe Changes: Main Steps.
|
|||
When a WebLogic Server resource generates a log message, the server’s
weblogic.management.runtime.LogBroadcasterRuntimeMBean emits a notification of type weblogic.management.logging.WebLogicLogNotification , which can be cast as the standard javax.management.Notification class.
To listen for log message notifications, register a listener with
LogBroadcasterRuntimeMBean . You can listen for the standard JMX notifications, or if you want to retrieve detailed information about the log messages, listen for WebLogicLogNotification s, which contains methods that you can use to retrieve detailed information. Listening for WebLogicLogNotification s requires you to import this WebLogic Server class into your listener class.
To see a list of error messages that WebLogic Server resources generate, refer to
WebLogic Server Message Catalogs.
For more information, see
WebLogicLogNotification in the WebLogic Server API Reference.
|
WebLogic Server MBeans provide detailed statistics on the runtime state of its services and resources. The statistics in Table 7-2 provide a general overview of the performance of WebLogic Server. You can listen for changes to these statistics by creating a listener and registering it directly with the MBeans that contain the attributes or you can configure monitor MBeans to periodically poll and report only the statistics that you consider to be significant. (See Registering a Notification Listener and Filter and Registering the Monitor and Listener.)
MBean Type:
ServerLifeCycleRuntimeMBean
|
|
MBean Type:
ServerMBean
|
|
MBean Type:
ThreadPoolRuntimeMBean
|
|
MBean Type:
ThreadPoolRuntimeMBean
|
|
MBean Type:
JVMRuntimeMBean
|
|
MBean Type:
JDBCDataSourceRuntimeMBean
|
|
MBean Type:
JDBCDataSourceRuntimeMBean
|
|
MBean Type:
JDBCDataSourceRuntimeMBean
Indicates the total number of leaked connections. Leaked connections are connections that have been checked out but never returned to the connection pool via a
close() call; it is important to monitor the total number of leaked connections, as a leaked connection cannot be used to fulfill later connection requests.
|
|
MBean Type:
JDBCDataSourceRuntimeMBean
|
|
MBean Type:
JDBCDataSourceRuntimeMBean
|
To listen directly for the notifications that an MBean emits:
To create a notification listener:
javax.management.NotificationListener
.
See
NotificationListener
in the J2SE 5.0 API Specification.
NotificationListener.handleNotification(Notification notification, java.lang.Object handback)
method.Note: | Your implementation of this method should return as soon as possible to avoid blocking its notification broadcaster. |
Type
attribute, which is used to classify the type of event that caused the notification to be emitted.
To retrieve information from a notification object, within your handleNotification
method invoke the object’s methods. Because all notification types extend javax.management.Notification
, the following Notification
methods are available for all notifications:
getMessage()
getSequenceNumber()
getTimeStamp()
getType()
getUserData()
See
Notification
in the J2SE 5.0 API Specification.
Most notification types provide additional methods for retrieving data that is specific to the notification. For example, javax.management.AttributeChangeNotification
provides getNewValue()
and getOldValue()
, which you can use to determine how the attribute value has changed.
Listing 7-1 is a simple listener that uses AttributeChangeNotification methods to retrieve the name of an attribute with a changed value, and the old and new values.
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.AttributeChangeNotification;
public class MyListener implements NotificationListener {
public void handleNotification(Notification notification, Object obj) {
if(notification instanceof AttributeChangeNotification) {
AttributeChangeNotification attributeChange =
(AttributeChangeNotification) notification;
System.out.println("This notification is an
AttributeChangeNotification");
System.out.println("Observed Attribute: " +
attributeChange.getAttributeName() );
System.out.println("Old Value: " + attributeChange.getOldValue() );
System.out.println("New Value: " + attributeChange.getNewValue() );
}
}
}
As of JMX 1.2, there are no special requirements for programming a listener that runs in a different JVM from the MBean to which it is listening.
Once you establish a connection to the remote JMX agent (using javax.management.MBeanServerConnection
), JMX takes care of sharing data between the JVMs. See
Registering a Notification Listener and Filter on page 7-11 for instructions on establishing a connection from a remote JVM.
Consider the following recommendations while creating your NotificationListener
class:
Instead of using one listener for all possible notifications that an MBean emits, the best practice is to use a combination of filters and listeners. While having multiple listeners adds to the amount of time for initializing the JVM, the trade-off is ease of code maintenance.
For example, if your WebLogic Server domain contains three JDBC data sources, you can create one listener class that listens for AttributeChangeNotifications
. Then, you create three registration classes. Each registration class registers the listener with a specific instance of JDBCDataSourceRuntimeMBean
.
handleNotification
method signature includes an argument for a handback object, your listener does not need to retrieve data from or otherwise manipulate the handback object. It is an opaque object that helps the listener to associate information regarding the MBean emitter.handleNotification
method should return as soon as possible to avoid blocking its notification broadcaster.if
statement to prevent your listener from invoking the method on notification objects of all types.As of JDK 1.5, the JDK includes two simple filter classes that you can configure to forward notifications that match criteria that you specify. To configure one of the JDK’s filter classes:
javax.management.NotificationFilterSupport
or AttributeChangeNotificationFilter
.
See
NotificationFilterSupport
or
AttributeChangeNotificationFilter
in the J2SE 5.0 API Specification.
For example, the following lines of code configure an AttributeChangeNotificationFilter
that forwards only attribute change notifications and only if there is a change in an attribute named State
:
AttributeChangeNotificationFilter filter =
new AttributeChangeNotificationFilter();
filter.enableAttribute("State");
If the JDK’s filter class is too simplistic for your needs, you can create more sophisticated, custom filter classes. (See
NotificationFilter
in the J2SE 5.0 API Specification.) However, BEA recommends that you use the JDK filter classes whenever possible: using a custom filter complicates the packaging and deployment of your listener and filter. See Packaging and Deploying Listeners on WebLogic Server.
After you implement a notification listener class, you create an additional class that registers your listener (and optionally configures and registers a filter) with an MBean instance.
To register a notification listener and filter with an MBean:
See Make Remote Connections to an MBean Server.
To register with a custom MBean, create an ObjectName
that contains the MBean’s JMX object name. See
javax.management.ObjectName
in the J2SE 5.0 API Specification.
MBeanServerConnection.addNotificationListener (
ObjectName
name
, ObjectName
listener
, NotificationFilter
filter
,
Object
handback
)
method.
The example class registers the listener from Listing 7-1 and the JDK’s AttributeChangeNotificationFilter
with all ServerLifeCycleRuntimeMBeans in a domain. The class does not pass a handback object.
In the example, weblogic
is a user who has permission to view and modify MBean attributes. For information about permissions to view and modify MBeans, refer to "Security Roles" in the Securing WebLogic Resources guide.
The example class also includes some code that keeps the RegisterListener
class active and not exit the main program. Usually this code is not necessary because a listener class runs in the context of some larger application that is responsible for invoking the class and keeping it active. It is included here so you can easily compile and see the example working.
import java.util.Hashtable;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.management.AttributeChangeNotificationFilter;
public class RegisterListener {
private static MBeanServerConnection connection;
private static JMXConnector connector;
private static final ObjectName service;
// Initializing the object name for DomainRuntimeServiceMBean
// so it can be used throughout the class.
static {
try {
service = new ObjectName(
"com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanserv
ers.domainruntime.DomainRuntimeServiceMBean");
}catch (MalformedObjectNameException e) {
throw new AssertionError(e.getMessage());
}
}
/*
* Initialize connection to the Domain Runtime MBean server
* each server in the domain hosts its own instance.
*/
public static void initConnection(String hostname, String portString,
String username, String password) throws IOException,
MalformedURLException {
String protocol = "t3";
Integer portInteger = Integer.valueOf(portString);
int port = portInteger.intValue();
String jndiroot = "/jndi/";
String mserver = "weblogic.management.mbeanservers.domainruntime";
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port,
jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
"weblogic.management.remote");
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
}
/*
* Get an array of ServerLifeCycleRuntimeMBeans
*/
public static ObjectName[] getServerLCRuntimes() throws Exception {
ObjectName domainRT = (ObjectName) connection.getAttribute(service,
"DomainRuntime");
return (ObjectName[]) connection.getAttribute(domainRT,
"ServerLifecycleRuntimes");
}
public static void main(String[] args) throws Exception {
String hostname = args[0];
String portString = args[1];
String username = args[2];
String password = args[3];
try {
//Instantiating your listener class.
MyListener listener = new MyListener();
AttributeChangeNotificationFilter filter =
new AttributeChangeNotificationFilter();
filter.enableAttribute("State");
initConnection(hostname, portString, username, password);
//Passing the name of the MBeans and your listener class to the
//addNotificationListener method of MBeanServer.
ObjectName[] serverLCRT = getServerLCRuntimes();
int length= (int) serverLCRT.length;
for (int i=0; i < length; i++) {
connection.addNotificationListener(serverLCRT[i], listener,
filter, null);
System.out.println("\n[myListener]: Listener registered with"
+serverLCRT[i]);
}
//Keeping the remote client active.
System.out.println("pausing...........");
System.in.read();
} catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
You can package and deploy a JMX listener as a remote application, a WebLogic Server startup class (which makes the listener available as soon as a server boots), or within one of your other applications that you deploy on WebLogic Server.
If you use a filter from the JDK, you do not need to package the filter class. It is always available through the JDK.
Table 7-3 describes how to package and deploy your listeners and any custom filters.
Also add the filter class to the classpath of each server instance that hosts the monitored MBeans by archiving the class in a JAR file and copying the JAR in each server’s
lib directory. See
Domain Directory Contents in Understanding Domain Configuration.
|
||
Add the filter class to the server’s classpath by archiving the class in a JAR file and copying the JAR in the server’s
lib directory. See
Domain Directory Contents in Understanding Domain Configuration.
|
||
Also add the filter class to the classpath of each server instance that hosts the monitored MBeans by doing one of the following:
|
When you create a WebLogic Server resource, such as a server or a JDBC data source, WebLogic Server creates a configuration MBean and registers it in the Domain Runtime MBean Server.
To listen for these events, register a listener with javax.management.MBeanServerDelegate
, which emits a notification of typejavax.management.MBeanServerNotification
each time an MBean is registered or unregistered. See
MBeanServerDelegate
in the J2SE 5.0 API Specification.
Note the following about the example listener in Listing 7-3:
ServerRuntimeMBean
contain the Type=ServerRuntime
key property in their object names.Type
attribute, whose value offers a way to categorize and filter notifications. The Type
attribute in MBeanServerNotification
contains only one of two possible strings: "JMX.mbean.registered" or "JMX.mbean.unregistered". JMX notifications also contain a getType
method that returns the value of the Type
attribute.
The listener in Listing 7-3 invokes different lines of code depending on the value of the Type
attribute.
JDBCDataSourceRuntimeMBean
has been registered, the listener passes the MBeans’ object name to a custom method. The custom method registers a listener and configures a filter for the JDBCDataSourceRuntimeMBean
; this MBean listener emits messages when the MBean’s Enabled
attribute changes. The implementation of the custom method is located in the registration class (not the filter class) so that the method can reuse registration class’s connection to the MBean server. Such reuse is an efficient use of resources and eliminates the need to store credentials and URLs in multiple classes.
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.MBeanServerNotification;
import javax.management.ObjectName;
public class DelegateListener implements NotificationListener {
public void handleNotification(Notification notification, Object obj) {
if (notification instanceof MBeanServerNotification) {
MBeanServerNotification msnotification =
(MBeanServerNotification) notification;
// Get the value of the MBeanServerNotification
// Type attribute, which contains either
// "JMX.mbean.registered" or "JMX.mbean.unregistered"
String nType = msnotification.getType();
// Get the object name of the MBean that was registered or
// unregistered
ObjectName mbn = msnotification.getMBeanName();
// Object names for WebLogic Server MBeans always contain
// a "Type" key property, which indicates the
// MBean's type (such as ServerRuntime or Log)
String key = mbn.getKeyProperty("Type");
if (nType.equals("JMX.mbean.registered")) {
System.out.println("A " + key + " has been created.");
System.out.println("Full MBean name: " + mbn);
System.out.println("Time: " + msnotification.getTimeStamp());
if (key.equals("JDBCDataSourceRuntime")) {
// Registers a listener with a ServerRuntimeMBean.
// By defining the "registerwithServerRuntime" method
// in the "ListenToDelegate" class, you can reuse the
// connection that "ListenToDelegate" established;
// in addition to being an efficient way to use resources,
// it eliminates the need to store credentials and URLs in
// multiple classes.
ListenToDelegate.registerwithJDBCDataSourceRuntime(mbn);
}
}
if (nType.equals("JMX.mbean.unregistered")) {
System.out.println("An MBean has been unregistered");
System.out.println("Server name: " +
mbn.getKeyProperty("Name"));
System.out.println("Time: " + msnotification.getTimeStamp());
System.out.println("Full MBean name: "
+ msnotification.getMBeanName());
}
}
}
}
Listing 7-4 shows methods from a registration class. Note the following:
MBeanServerDelegate
is always "JMImplementation:type=MBeanServerDelegate"
.main
method configures an instance of javax.management.NotificationFilterSupport
to forward notifications only if value of the notification’s Type attribute starts with "JMX.mbean.registered" or "JMX.mbean.unregistered".registerwithJDBCDataSourceRuntime
method registers the listener in Listing 7-1 with the specified JDBCDataSourceRuntimeMBean
instance. The method also configures a javax.management.AttributeChangeNotificationFilter
, which forwards only AttributeChangeNotification
s that describe changes to an attribute named Enabled
.To compile and run these methods, use the supporting custom methods from Listing 7-2 and run the resulting class as a remote JMX client.
public static void main(String[] args) throws Exception {
String hostname = args[0];
String portString = args[1];
String username = args[2];
String password = args[3];
ObjectName delegate = new ObjectName(
"JMImplementation:type=MBeanServerDelegate");
try {
//Instantiating your listener class.
StartStopListener slistener = new StartStopListener();
NotificationFilterSupport filter = new NotificationFilterSupport();
filter.enableType("JMX.mbean.registered");
filter.enableType("JMX.mbean.unregistered");
/* Invoke a custom method that establishes a connection to the
* Domain Runtime MBean Server and uses an instance of
* MBeanServerConnection to represents the connection. The custom
* method assigns the MBeanServerConnection to a class-wide, static
* variable named "connection".
*/
initConnection(hostname, portString, username, password);
//Passing the name of the MBeans and your listener class to the
//addNotificationListener method of MBeanServer.
connection.addNotificationListener(delegate, slistener, filter,
null);
System.out.println("\n[myListener]: Listener registered ...");
//Keeping the remote client active.
System.out.println("pausing...........");
System.in.read();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
// Called by the listener if it receives notification of a
// JDBCDataSourceRuntimeMBean being registered.
public static void registerwithJDBCDataSourceRuntime(ObjectName mbname) {
try {
MyListener mylistener = new MyListener();
AttributeChangeNotificationFilter filter =
new AttributeChangeNotificationFilter();
filter.enableAttribute("Enabled");
connection.addNotificationListener(mbname, mylistener,
filter, null);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
To configure and use monitor MBeans:
JMX provides monitor MBeans that are specialized to observe specific types of changes:
StringMonitorMBean
observes attributes whose value is a String
.
Use this monitor to periodically observe attributes such as ServerLifeCycleRuntimeMBean
State
.
See
javax.management.monitor.StringMonitor
in the J2SE 5.0 API Specification, which implements StringMonitorMBean
.
GaugeMonitorMBean
observes attributes whose value is a Number
.
Use this monitor to observe an attribute whose value fluctuates as a result of normal operations. Configure the gauge monitor to emit a notification if the value of the attribute fluctuates outside a specific range. For example, you can use it to monitor the ThreadPoolRuntimeMBean
StandbyThreadCount
attribute to verify that the number of unused but available threads in a server falls within an acceptable range.
See
javax.management.monitor.GaugeMonitor
in the J2SE 5.0 API Specification, which implements GaugeMonitorMBean
.
CounterMonitorMBean
observes attributes whose value is a Number
. Use this monitor to observe an attribute whose value only increases as a result of normal operation. Configure the counter monitor to emit a notification if the value of the attribute crosses an upper threshold. You can also configure the counter monitor to increase the threshold and then reset the threshold at a specified point.
For example, to track the overall number of hits on a server and to be notified each time 100 additional hits have accumulated, use a counter monitor that observes the ServerRuntimeMBean
SocketsOpenedTotalCount
attribute.
See
javax.management.monitor.CounterMonitor
in the J2SE 5.0 API Specification, which implements CounterMonitorMBean
.
All monitor MBeans emit notifications of type javax.management.monitor.MonitorNotification
. When a monitor MBean generates a notification, it describes the event that generated the notification by writing a specific value into the notification’s Type
property. Table 7-4 describes the value of the Type
property that the different types of monitor MBeans encode. A filter or listener can use the notification’s getType()
method to retrieve the String
in the Type
property.
If an error occurs, all monitors encode one of the following values in the notification’s Type
property:
jmx.monitor.error.mbean
, which indicates that the observed MBean is not registered in the MBean Server. The observed object name is provided in the notification.jmx.monitor.error.attribute
, which indicates that the observed attribute does not exist in the observed object. The observed object name and observed attribute name are provided in the notification.jmx.monitor.error.type
, which indicates that the object instance of the observed attribute value is null
or not of the appropriate type for the given monitor. The observed object name and observed attribute name are provided in the notification.jmx.monitor.error.runtime
, which contains exceptions that are thrown while trying to get the value of the observed attribute (for reasons other than the cases described above).
The counter and the gauge monitors can also encode jmx.monitor.error.threshold
into the Type
property under the following circumstances:
When an observed attributes meets the criteria that you specify, a monitor MBean emits a notification. There are no special requirements for creating a listener for a MonitorNotification
. The steps are the same as those described in Creating a Notification Listener except:
See Listing 7-5.
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.monitor.MonitorNotification;
public class MonitorListener implements NotificationListener {
public void handleNotification(Notification notification, Object obj) {
if(notification instanceof Notification) {
Notification notif = (Notification) notification;
System.out.println("Notification type" + notif.getType() );
System.out.println("Message: " + notif.getMessage() );
}
if (notification instanceof MonitorNotification) {
MonitorNotification mn = (MonitorNotification) notification;
System.out.println("Observed Attribute: " +
mn.getObservedAttribute());
System.out.println("Trigger: " + mn.getTrigger() );
}
}
}
Recall that to use a monitor MBean, you first must create and register an instance of the monitor MBean in the MBean server. Then you register a listener with the monitor MBean that you created. You can do all of this in a single class.
To register a monitor MBean, register your listener, and start the monitor MBean:
See Make Remote Connections to an MBean Server.
ObjectName
for your monitor MBean instance.
See
javax.management.ObjectName
in the J2SE 5.0 API Specification.
BEA recommends that your object name starts with the name of your organization and includes key properties that clearly identifies the purpose of the monitor MBean instance.
For example, mycompany:Name=SocketMonitor,Type=CounterMonitor
Use javax.management.MBeanServerConnection.createMBean(String
classname
ObjectName
name
)
method where:
For guidelines on which attributes to set, see the
javax.management.monitoring
package in the J2SE 5.0 API Specification.
addObservedObject(ObjectName o
bjectname
)
and addObservedAttribute(String
attributename
)
operations where.objectname
is the ObjectName
of the observed MBeanattributename
is the name of the attribute in the observed MBean that you want to monitor
A single instance of a monitor MBean can monitor multiple MBeans. Invoke the addObservedObject
and addObservedAttribute
operation for each MBean instance that you want to monitor.
Invoke the monitor MBean’s addNotificationListener(NotificationListener
listener
, NotificationFilter
filter
, Object
handback
)
method.
start()
operation.
Listing 7-6 shows the main()
method of a class that creates and configures a CounterMonitorMBean
to observe the SocketsOpenedTotalCount
attribute in each ServerRuntimeMBean
instance in a domain. (See
SocketsOpenedTotalCount
in WebLogic Server MBean Reference.)
The code example connects to the Domain Runtime MBean Server so that it can monitor multiple instances of ServerRuntimeMBean
. Note the following:
CounterMonitorMBean
monitors all instances of ServerRuntimeMBean
. The Domain Runtime MBean Server gives the CounterMonitorMBean
federated access to instances of ServerRuntimeMBean
that are running in a different JVM.CounterMonitorMBean
.To compile and run this main method, use the supporting custom methods from Listing 7-2 and run the resulting class as a remote JMX client.
public static void main(String[] args) throws Exception {
String hostname = args[0];
String portString = args[1];
String username = args[2];
String password = args[3];
try {
/* Invokes a custom method that establishes a connection to the
* Domain Runtime MBean Server and uses an instance of
* MBeanServerConnection to represents the connection. The custom
* method assigns the MBeanServerConnection to a class-wide, static
* variable named "connection".
*/
initConnection(hostname, portString, username, password);
//Creates and registers the monitor MBean.
ObjectName monitorON =
new ObjectName("mycompany:Name=mySocketMonitor,Type=CounterMonitor");
String classname = "javax.management.monitor.CounterMonitor";
System.out.println("===> create mbean "+monitorON);
connection.createMBean(classname, monitorON);
//Configure the monitor MBean.
Number initThreshold = new Long(2);
Number offset = new Long(1);
connection.setAttribute(monitorON,
new Attribute("InitThreshold", initThreshold));
connection.setAttribute(monitorON, new Attribute("Offset", offset));
connection.setAttribute(monitorON,
new Attribute("Notify", new Boolean(true)));
//Gets the object names of the MBeans that you want to monitor.
ObjectName[] serverRT = getServerRuntimes();
int length= (int) serverRT.length;
for (int i=0; i < length; i++) {
//Sets each instance of ServerRuntime MBean as a monitored MBean.
System.out.println("===> add observed mbean "+serverRT[i]);
connection.invoke(monitorON, "addObservedObject",
new Object[] { serverRT[i] },
new String[] { "javax.management.ObjectName" });
Attribute attr = new Attribute("ObservedAttribute",
"SocketsOpenedTotalCount");
connection.setAttribute(monitorON, attr);
}
// Instantiates your listener class and configures a filter to
// forward only counter monitor messages.
MonitorListener listener = new MonitorListener();
NotificationFilterSupport filter = new NotificationFilterSupport();
filter.enableType("jmx.monitor.counter");
filter.enableType("jmx.monitor.error");
//Uses the MBean server's addNotificationListener method to
//register the listener and filter with the monitor MBean.
System.out.println("===> ADD NOTIFICATION LISTENER TO "+monitorON);
connection.addNotificationListener(monitorON, listener, filter, null);
System.out.println("\n[myListener]: Listener registered ...");
//Starts the monitor.
connection.invoke(monitorON, "start", new Object[] { }, new String[] { });
//Keeps the remote client active.
System.out.println("pausing...........");
System.in.read();
} catch(Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
}
![]() ![]() ![]() |