Saturday, May 16, 2009

JMX - Exposing an mbean

JMX is an easy-to-utilize way to expose some of the key inner-workings of your application in a standardized way, so you can maximize the
manageability and monitoring facilities of your application.

A standard MBean is defined by writing a Java interface called SomethingMBean and a Java class called Something that implements that interface.
Every method in the interface defines either an attribute or an operation in the MBean. By default, every method defines an operation.


MBean Interface


public interface TestMBean
{
public void sayHello();
public int add(int x, int y);
}

By convention, an MBean interface takes the name of the Java class that implements it, with the suffix MBean added.

Meab Implementation

public class Test implements TestMBean {
public void sayHello() {
System.out.println("hello, world");
}

public int add(int x, int y) {
return x + y;
}

}

Creating a JMX Agent to Manage a Resource

public class Main {

public static void main(String[] args) throws Exception {

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=Test");
Test mbean = new Test();
mbs.registerMBean(mbean, name);

.....

System.out.println("Waiting forever...");
Thread.sleep(Long.MAX_VALUE);
}
}


The object name is an instance of the JMX class ObjectName and must conform to the syntax defined by the JMX specification. Namely, the object name
must contain a domain and a list of key-properties. In the object name defined by Main, the domain is com.example (the package in which the example
MBean is contained). In addition, the key-property declares that this object is of the type Test.


An instance of a Test object, named mbean, is created. The Hello object named mbean is then registered as an MBean in the MBean server mbs with the
object name name, by passing the object and the object name into a call to the JMX method MBeanServer.registerMBean().

Running the Standard MBean Example


Run the sample application

Connect using jconsole and these operations can be directly called from there and values can be set.

No comments:

 
Free Domain Names @ .co.nr!